#K48672. Longest Subarray with Sum at Most K
Longest Subarray with Sum at Most K
Longest Subarray with Sum at Most K
Given a sequence of integers and a constant integer \( k \), your task is to find the length of the longest contiguous subarray such that the sum of its elements is less than or equal to \( k \). This problem can be efficiently solved using a two-pointer (or sliding window) technique.
Problem Statement: Given an integer \( n \) representing the number of elements in the sequence, an integer \( k \), and a list of \( n \) integers, determine the length of the longest contiguous subarray where the sum does not exceed \( k \).
Examples:
- For input
n=5
,k=5
, and the sequence[1, 2, 3, 4, 5]
, the output is2
. - For input
n=6
,k=10
, and the sequence[6, 7, 1, 2, 5, 4]
, the output is3
.
The algorithm must correctly handle cases where no subarray meets the condition (output \( 0 \)) as well as cases with possible zero values in the sequence.
inputFormat
The first line contains two space-separated integers \( n \) and \( k \), where \( n \) is the number of elements in the sequence and \( k \) is the maximum allowed sum for any valid subarray.
The second line contains \( n \) space-separated integers representing the sequence.
outputFormat
Output a single integer: the length of the longest contiguous subarray with a sum less than or equal to \( k \).
## sample5 5
1 2 3 4 5
2