#K41647. Longest Contiguous Subarray with Sum Constraint

    ID: 26912 Type: Default 1000ms 256MiB

Longest Contiguous Subarray with Sum Constraint

Longest Contiguous Subarray with Sum Constraint

Given an array of integers and an integer \(k\), your task is to find the length of the longest contiguous subarray whose sum does not exceed \(k\). This problem can be efficiently solved using a sliding window (two-pointers) technique.

Example:

Input: 6 15
       1 2 3 4 5 6
Output: 5

The expected output is 5 because the subarray \([1,2,3,4,5]\) is the longest subarray with a sum (15) that does not exceed \(k = 15\).

inputFormat

The input is provided via standard input and consists of two lines:

  • The first line contains two integers \(n\) and \(k\): \(n\) is the number of elements in the array and \(k\) is the maximum allowed sum.
  • The second line contains \(n\) integers separated by spaces representing the array elements.

outputFormat

Output a single integer on standard output: the length of the longest contiguous subarray whose sum is not more than \(k\).

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