11. K-th Largest Sum Contiguous Subarray
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given an array arr[]
of size n
, find the sum of the K-th largest sum among all possible contiguous subarrays of arr
. In other words, list all contiguous subarray sums, sort them in descending order, and return the K-th element.
๐ Examples
Example 1:
Input:
arr[] = [3, 2, 1], k = 2
Output:
5
Explanation:
All contiguous subarray sums are [6, 5, 3, 2, 1]
. The 2nd largest is 5
.
Example 2:
Input:
arr[] = [2, 6, 4, 1], k = 3
Output:
11
Explanation:
All sums are [13, 12, 11, 10, 8, 6, 5, 4, 2, 1]
. The 3rd largest is 11
.
๐ Constraints
$1 \leq n \leq 1000$
$1 \leq k \leq \dfrac{n(n+1)}{2}$
$-10^5 \leq arr[i] \leq 10^5$
โ
My Approach
Prefix Sums + Min-Heap
Compute prefix sums array
P
of lengthn+1
, where $P[0] = 0,\quad P[i] = P[i-1] + arr[i-1]\quad (1 \le i \le n).$Use a min-heap (
priority_queue<int, vector<int>, greater<int>>
) of size up tok
to keep track of the k largest sums seen so far.Enumerate all subarrays by two loops
i
from0
ton-1
,j
fromi+1
ton
:Compute current sum
S = P[j] - P[i]
.Push
S
into the heap; if size exceedsk
, pop the smallest.
After processing all, the top of the min-heap is the K-th largest sum.
๐งฎ Time and Auxiliary Space Complexity
Expected Time Complexity: $O(n^2 \log k)$, due to the double loop over subarrays ($O(n^2)$) and heap operations ($O(\log k)$).
Expected Auxiliary Space Complexity: $O(k)$, for storing at most k sums in the heap.
๐ง Code (C++)
class Solution {
public:
int kthLargest(vector<int> &arr, int k) {
vector<int> p(arr.size() + 1);
for (int i = 0; i < arr.size(); ++i) p[i + 1] = p[i] + arr[i];
priority_queue<int, vector<int>, greater<int>> q;
for (int i = 0; i < arr.size(); ++i)
for (int j = i + 1; j <= arr.size(); ++j) {
q.push(p[j] - p[i]);
if (q.size() > k) q.pop();
}
return q.top();
}
};
๐งโ๐ป Code (Java)
class Solution {
public static int kthLargest(int[] arr, int k) {
int[] p = new int[arr.length + 1];
for (int i = 0; i < arr.length; ++i) p[i + 1] = p[i] + arr[i];
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 0; i < arr.length; ++i)
for (int j = i + 1; j <= arr.length; ++j) {
q.add(p[j] - p[i]);
if (q.size() > k) q.poll();
}
return q.peek();
}
}
๐ Code (Python)
class Solution:
def kthLargest(self, arr, k) -> int:
p = [0]
for x in arr: p.append(p[-1] + x)
q = []
for i in range(len(arr)):
for j in range(i + 1, len(arr) + 1):
heapq.heappush(q, p[j] - p[i])
if len(q) > k: heapq.heappop(q)
return q[0]
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated