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 = 2Output:
5Explanation:
All contiguous subarray sums are [6, 5, 3, 2, 1]. The 2nd largest is 5.
Example 2:
Input:
Output:
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
Pof 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 tokto keep track of the k largest sums seen so far.Enumerate all subarrays by two loops
ifrom0ton-1,jfromi+1ton:Compute current sum
S = P[j] - P[i].Push
Sinto 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++)
🧑💻 Code (Java)
🐍 Code (Python)
🧠 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