This is the "Hard" version of the minimum cost subarray problem. You need to divide an array into contiguous subarrays such that the sum of the first elements of these subarrays is minimized. The first subarray must start at index 0. Additionally, there is a constraint on the "distance" between the first and last subarray heads: the index of the -th subarray head must be within a certain distance dist from the first subarray head (index 0).
Microsoft and American Express use this to test your mastery of Sliding Window and Priority Queues. It evaluation whether you can maintain a set of "top " elements within a moving window. This is a significant step up in complexity, requiring you to efficiently add and remove elements from a "lowest values" collection as the window slides across the array.
This problem uses a Sliding Window combined with a Multi-Set or two Heaps.
nums[0]. You need to pick more elements from a window of size dist + 1.nums[0] is a candidate for the minimum cost.nums = [1, 3, 2, 6, 4, 2], , dist=3.
[1, 4] (since dist=3, index must be ? actually the rule is ).TreeMap or a lazy-removal heap.dist.Practice the Sliding Window with Top-K pattern. This requires two balanced structures (like two TreeSets in Java or two heaps with counts) to keep track of the sum of the smallest elements in time per update.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sliding Window Median | Hard | Solve | |
| Find X-Sum of All K-Long Subarrays II | Hard | Solve | |
| Find X-Sum of All K-Long Subarrays I | Easy | Solve | |
| Number of Unique Flavors After Sharing K Candies | Medium | Solve | |
| Maximum Erasure Value | Medium | Solve |