Description
Given an array a whose length is n. Return the kth subarray ranked by sums of subarrays.1 <= n <= 10^51 <= a <= 10^9
Solution
The maximum sum of a subarray is bounded by n * a which is 10^14, so we can use a binary search approach to find the kth subarray. Now the problem is how to check the mid of each binary search iteration.
I use an approach similar to prefix sum. The program maintains three variables left, right, and cur_sum(similar to prefix[right]-prefix[left]).
On each iteration, the right index is increased to the right most index which that makes the cur_sum lower or equal to our target, and we can know that there are len(a)-right subarrays that sum greater than our target. The left is then increased by one and the next iteration starts.
Here is my code:
1 | class Solution: |
Analysis
This solution is O(n * log(n)), where the binary search part runs log(n) times rank function( O(n) ).