FastPrepLongest Subarray with Sum at Most K
Problem · Array

Longest Subarray with Sum at Most K

Learn this problem
HardGoogle logoGoogleINTERNOA
See Google hiring insights

Problem statement

Given an integer array nums and an integer k, return the maximum length of a non-empty contiguous subarray whose sum is at most k.

The array may contain positive, zero, and negative values, so a standard positive-only sliding window is not sufficient.

Return 0 when no non-empty subarray satisfies the limit.

Function

longestSubarrayAtMostK(nums: int[], k: long) → int

Examples

Example 1

nums = [1,2,-1,2]k = 3return = 3

The subarray [1, 2, -1] has sum 2 and length 3. The full array has sum 4.

Example 2

nums = [5,-10,5]k = 0return = 3

The entire array sums to 0; the negative value makes the longest valid window non-monotonic.

Constraints

  • 1 <= nums.length <= 200000
  • -10^9 <= nums[i] <= 10^9
  • -10^14 <= k <= 10^14
  • Subarray sums fit in a signed 64-bit integer.

More Google problems

drafts saved locally
public int longestSubarrayAtMostK(int[] nums, long k) {
  // Write your code here.
}
nums[1,2,-1,2]
k3
expected3
checking account