Sponsored
Sponsored
Use these hints if you're stuck. Try solving on your own first.
For each <code>i > 0</code>, try each <code>nums[i]</code> as the first element of the second subarray. We need to find the sum of <code>k - 2</code> smallest values in the index range <code>[i + 1, min(i + dist, n - 1)]</code>.
Typically, we use a max heap to maintain the top <code>k - 2</code> smallest values dynamically. Here we also have a sliding window, which is the index range <code>[i + 1, min(i + dist, n - 1)]</code>. We can use another min heap to put unselected values for future use.
Update the two heaps when iteration over <code>i</code>. Ordered/Tree sets are also a good choice since we have to delete elements.
If the max heap’s size is less than <code>k - 2</code>, use the min heap’s value to fill it. If the maximum value in the max heap is larger than the smallest value in the min heap, swap them in the two heaps.