Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the longest subarray with sum at most K

Given a non-negative integer array and a target K, find the length of the longest contiguous subarray whose sum is <= K using sliding window.

Python practice16 minTwo Pointers & Sliding WindowIntermediateLast updated March 26, 2026

Problem statement

Given an array of non-negative integers arr and an integer K, return the length of the longest contiguous subarray whose sum is less than or equal to K. If no such subarray exists, return 0. Because all numbers are non-negative, a sliding window (two-pointer) approach can be used to maintain subarray sum efficiently.

Task

Implement an O(n) sliding window solution that returns the length of the longest contiguous subarray with sum at most K.

Examples

Simple example

Input

arr = [1, 2, 3, 4, 5], K = 10

Output

4

The subarray [1,2,3,4] has sum 10 and length 4, which is the longest with sum <= 10.

Input format

Two inputs: a list of non-negative integers arr and an integer K.

Output format

An integer representing the length of the longest contiguous subarray with sum <= K.

Constraints

0 <= len(arr) <= 10^5; 0 <= arr[i] <= 10^9; 0 <= K <= 10^18. Expected time: O(n), extra space: O(1).

Samples

Sample 1

Input

[3,1,2,1,1], 4

Output

3

Subarray [1,2,1] has sum 4 and length 3.