#K79927. Maximum Subarray Length with Sum Constraint

    ID: 35417 Type: Default 1000ms 256MiB

Maximum Subarray Length with Sum Constraint

Maximum Subarray Length with Sum Constraint

You are given an array of positive integers and a target sum \(s\). The task is to find the maximum number of contiguous elements (a subarray) such that the sum of those elements is at most \(s\). In other words, you need to find the length of the longest subarray whose total sum does not exceed \(s\).

Input: The input is provided via standard input. The first line contains two integers \(n\) and \(s\), where \(n\) is the number of elements in the array and \(s\) is the maximum allowed sum. The second line contains \(n\) space-separated positive integers representing the array.

Output: Print a single integer, which is the maximum length of a contiguous subarray with a sum less than or equal to \(s\).

Constraints:

  • \(1 \leq n \leq 10^5\)
  • \(1 \leq s \leq 10^9\)
  • All array elements are positive integers.

This problem can be efficiently solved using a sliding window (two-pointer) technique.

inputFormat

The input is read from standard input. The first line contains two integers \(n\) and \(s\) separated by a space. The second line contains \(n\) space-separated integers representing the array.

outputFormat

Output to standard output a single integer representing the maximum length of a contiguous subarray whose sum is less than or equal to \(s\).

## sample
5 6
1 2 3 2 1
3