Dsa
Sliding Window
Hard
K-Max Budget Allocation
You are managing a sequence of tasks with varying resource costs. You want to find the longest sequence of contiguous tasks such that the sum of the costs of the K most expensive tasks in that sequence does not exceed a budget B. If a sequence has fewer than K tasks, all its tasks are considered.
Input Format:
- Line 1: Two integers, K and B.
- Line 2: Integer N (number of tasks).
- Line 3: N space-separated integers (costs).
Output Format:
- A single integer (max length).
Example:
Input:
2 10
5
1 8 2 9 1
Output:
3
(Explanation: Window [1, 8, 2] has top 2 costs {8, 2}, sum 10. Length 3. Window [8, 2, 9] top 2 are {8, 9}, sum 17 > 10.)
Key concepts
sliding_windowsorted_list
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