Dsa
Sliding Window
Hard
Periodic Constraint Window
Find the longest contiguous subarray such that the sum of all elements is at most S, and for every element at index 'i' in the subarray, if the element at index 'i-K' is also within the subarray, then 'arr[i]' must be strictly greater than 'arr[i-K]'.
Input Format:
- Line 1: Two integers, K (the period) and S (max sum).
- Line 2: Integer N.
- Line 3: N space-separated integers.
Output Format:
- A single integer representing the maximum length.
Example:
Input:
2 20
6
1 5 2 6 3 7
Output:
6
(Explanation: All pairs (arr[i-2], arr[i]) satisfy the condition: 2>1, 6>5, 3>2, 7>6. Total sum is 24, which is > 20. Window [1, 5, 2, 6, 3] sum is 17 <= 20. Length 5.)
Key concepts
sliding_windowmath
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