#C4228. Longest Contiguous Subarray with Sum Constraint

    ID: 47743 Type: Default 1000ms 256MiB

Longest Contiguous Subarray with Sum Constraint

Longest Contiguous Subarray with Sum Constraint

You are given an array of n integers and an integer M. 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 M.

More formally, given an array \(a_1, a_2, \dots, a_n\), find the maximum integer \(L\) such that there exists a pair of indices \(i\) and \(j\) with \(1 \leq i \leq j \leq n\) satisfying

[ \sum_{k=i}^{j} a_k \leq M ]

If no subarray exists that meets the condition, output 0. It is guaranteed that all elements in the array are non-negative.

Input/Output Format: The input is read from standard input and the output is written to standard output.

inputFormat

The first line contains an integer T, denoting the number of test cases.

Each test case consists of two lines:

  • The first line contains two space-separated integers: n (the number of elements in the array) and M (the maximum allowed sum).
  • The second line contains n space-separated integers representing the elements of the array.

Example:

5 7
1 2 3 4 5

outputFormat

For each test case, output a single integer on a new line representing the length of the longest contiguous subarray whose sum does not exceed M.

Example Output:

3
## sample
5
5 7
1 2 3 4 5
6 10
2 1 2 1 2 1
3 5
10 20 30
1 5
5
4 4
1 1 1 1
3

6 0 1 4

</p>