#K47562. Longest Contiguous Subarray with Sum at Most K

    ID: 28226 Type: Default 1000ms 256MiB

Longest Contiguous Subarray with Sum at Most K

Longest Contiguous Subarray with Sum at Most K

Given an array of positive integers and a target sum \(k\), find the length of the longest contiguous subarray whose sum does not exceed \(k\). This problem requires an efficient algorithm because the array length can be large.

The input begins with an integer \(T\) representing the number of test cases. Each test case consists of two lines:

  • The first line contains two integers: \(m\) (the number of elements in the array) and \(k\) (the target sum).
  • The second line contains \(m\) space-separated positive integers.

For each test case, your task is to determine the maximum length of a contiguous subarray with a sum that is at most \(k\). If no valid subarray exists, output 0.

Hint: Consider using the sliding window technique to solve this problem in linear time.

inputFormat

The input is given from standard input (stdin) in the following format:

  • The first line contains an integer \(T\), the number of test cases.
  • For each test case, the first line contains two integers \(m\) and \(k\), where \(m\) is the length of the array and \(k\) is the target sum.
  • The second line contains \(m\) space-separated positive integers representing the array elements.

outputFormat

For each test case, output a single line containing the length of the longest contiguous subarray whose sum is less than or equal to \(k\). If no such subarray exists, output 0.

## sample
2
6 15
1 2 3 4 5 6
4 5
4 1 1 1
5

3

</p>