Problem 445679 · medium · Level 04 Non-Linear Data Structures

The k-th Best Stretch of Takings

heaps · subarrays · kth element · bounded heap

A market stall's profit or loss for each day is listed in nums. Any run of one or more consecutive days is a stretch, and its takings are the sum of its days. Return the k-th largest takings over all stretches. Different stretches count separately even when their takings are equal: [1, 1] has stretches worth 1, 1, 2, so its 2nd largest is 1.

Examples

Input:  nums = [2, -1, 3], k = 2
Output: 3
Explanation: subarray sums are 2, -1, 3, 1 (2,-1), 2 (-1,3), 4 (2,-1,3).
             In descending order: 4, 3, 2, 2, 1, -1. The 2nd largest is 3.

Input:  nums = [1, 1], k = 3
Output: 1

Constraints

  • 1 <= len(nums) <= 500, -10**4 <= nums[i] <= 10**4
  • 1 <= k <= n * (n + 1) / 2 (the number of subarrays)
  • Target complexity: O(n^2 log k) time and O(k) extra space.

Goals

  • Enumerate all contiguous subarray sums with a running total
  • Keep only the k largest candidates in a min-heap of size k
  • Read the answer off the top of the bounded heap
Starting Python…