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 list of non-negative integers and a threshold k, find the maximum length of a contiguous subarray whose sum is <= k.

Python practice14 minArrays – Fundamentals & PatternsIntermediateLast updated March 25, 2026

Problem statement

You are given an array of non-negative integers nums and an integer k. Return the length of the longest contiguous subarray whose sum is less than or equal to k. Because all numbers are non-negative, a sliding-window (two-pointer) approach can be used to expand and contract a window while tracking its sum. If no subarray satisfies the condition, return 0.

Task

Implement an efficient sliding-window algorithm to compute the length of the longest contiguous subarray with sum at most k in O(n) time and O(1) extra space.

Examples

Basic example

Input

nums = [1, 2, 3, 4, 5], k = 7

Output

3

The longest subarray with sum <= 7 is [1,2,3] with length 3 (sum=6).

Input format

Function input: longest_subarray_at_most_k(nums, k) where nums is a list of non-negative integers and k is an integer.

Output format

Return an integer representing the maximum length of a contiguous subarray whose sum is <= k.

Constraints

0 <= len(nums) <= 10^5. 0 <= nums[i] <= 10^9. -10^18 <= k <= 10^18. Expected time O(n), extra space O(1).

Samples

Sample 1

Input

nums = [2, 1, 1, 1, 5, 1, 1], k = 4

Output

3

One longest subarray is [1,1,1] with sum 3 and length 3.