Dsa
Heap
Easy
The Rolling Top-K Sum
You are given an integer K and a stream of N integers. After each new integer is added to the stream, calculate the sum of the K largest integers seen so far. If the stream has fewer than K integers, calculate the sum of all integers seen so far.
Example:
K=2. Stream: [10, 5, 20, 15].
- Add 10: Sum is 10.
- Add 5: Top 2 are [10, 5], sum is 15.
- Add 20: Top 2 are [20, 10], sum is 30.
- Add 15: Top 2 are [20, 15], sum is 35.
Output: 10, 15, 30, 35 (on separate lines).
Key concepts
heapsliding-windowrunning-total
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now