![]() |
VOOZH | about |
Given an array arr[] of size n, the task is to find the kth largest sum of contiguous subarray within the array of numbers that has both negative and positive numbers.
Examples:
Input: arr[] = [20, -5, -1], k = 3
Output: 14
Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1), so the 3rd largest sum is 14.Input: arr[] = [10, -10, 20, -40], k = 6
Output: -10
Explanation: The 6th largest sum among sum of all contiguous subarrays is -10.
Table of Content
The idea is to calculate the Kth largest sum of contiguous subarrays by generating all possible contiguous subarray sums, storing them, and then sorting them in decreasing order to directly access the Kth largest. However, this approach can lead to memory issues when the input array size is large, as the number of contiguous subarrays grows quadratically with the size of the input array.
Step-by-Step Implementation:
14
The idea is to leverage a prefix-sum array to compute every contiguous subarray sum in constant time per pair of endpoints, collect all those sums into a single list, sort that list in descending order, and then directly pick out the Kth largest value.
Step-by-Step Implementation:
prefixSum of length n+1 where prefixSum[i] equals the total of the first i elements.i from 1 to n, and for each end index j from i to n, compute the subarray sum as prefixSum[j] – prefixSum[i–1] and append it to the list.k–1 in the sorted list as the Kth largest sum.14
The key idea is to store the pre-sum of the array in a sum[] array. One can find the sum of contiguous subarray from index i to j as sum[j] - sum[i-1]. After this step, this problem becomes same as k-th smallest element in an array. So we generate all possible contiguous subarray sums and push them into the Min-Heap only if the size of Min-Heap is less than K or the current sum is greater than the root of the Min-Heap. In the end, the root of the Min-Heap is the required answer.
Follow the given steps to solve the problem using the above approach:
14