Kth largest sum continuous subarrays
Pattern: Top K
There are n(n + 1)/2 subarray sums, each found in O(1) with prefix sums. Keep a min heap of the k largest sums seen; the top at the end is the answer. O(n² log k) time and O(k) memory.
The problem
Return the kth largest sum among all contiguous subarrays of arr. [3, 2, 1] with k = 2 gives 5 (the sums are
6, 5, 3, 3, 2, 1). [2, 6, 4, 1] with k = 3 gives 11.
Think first
- How many subarray sums are there?
- How do you get each sum in O(1)?
- Do you need to store all of them?
Hints
Brute force, and why it fails
Collect every sum and sort: O(n² log n) time and O(n²) memory.
The key insight
Prefix sums give each subarray sum instantly, and a size-k min heap keeps memory at O(k).
Dry run
| sums | 3 5 6 2 3 1 |
|---|
arr = [3, 2, 1], k = 2. The sums are 3, 5, 6 (starting at 0), 2, 3 (starting at 1) and 1.
Step 1 of 3
The plan
prefix[0] = 0; prefix[i + 1] = prefix[i] + arr[i]
for i, j with i <= j:
push prefix[j + 1] - prefix[i]; if size > k: pop
return top
Complexity
- Time
O(n² log k)- Space
O(n + k)
Every pair (i, j) is visited once with a heap step.
Edge cases
- k = 1: the maximum subarray sum.
- Negative values.
- Equal sums count separately.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int kthLargest(int[] arr, int k) {
int n = arr.length;
long[] prefix = new long[n + 1];
for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + arr[i];
PriorityQueue<Long> heap = new PriorityQueue<>(); // the k largest sums so far, smallest on top
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
heap.add(prefix[j + 1] - prefix[i]); // the sum of arr[i..j]
if (heap.size() > k) heap.poll();
}
}
return (int) (long) heap.peek();
}
}C++
class Solution {
public:
int kthLargest(vector<int>& arr, int k) {
int n = static_cast<int>(arr.size());
vector<long long> prefix(n + 1, 0);
for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + arr[i];
priority_queue<long long, vector<long long>, greater<long long>> heap; // the k largest sums, smallest on top
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
heap.push(prefix[j + 1] - prefix[i]); // the sum of arr[i..j]
if (static_cast<int>(heap.size()) > k) heap.pop();
}
}
return static_cast<int>(heap.top());
}
};Python
import heapq
class Solution:
def kthLargest(self, arr: list[int], k: int) -> int:
prefix = [0]
for x in arr:
prefix.append(prefix[-1] + x)
heap = [] # the k largest sums so far, smallest on top
for i in range(len(arr)):
for j in range(i, len(arr)):
heapq.heappush(heap, prefix[j + 1] - prefix[i]) # the sum of arr[i..j]
if len(heap) > k:
heapq.heappop(heap)
return heap[0]Common mistakes
- Removing duplicate sums.
- Using a max heap of all sums, which costs O(n²) memory.