FastPrepLongest Subarray with Sum at Most K
Problems/Longest Subarray with Sum at Most K

Longest Subarray with Sum at Most K

Google logoGoogle● HardINTERNOA
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source omits the callable interface, numeric bounds, and empty-result behavior. The judged core task matches the visible source at about 95%.

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

  • Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
  • Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
  • 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
All Google interview questionsSee Google hiring insights
Saved
class Solution {
    public int longestSubarrayAtMostK(int[] nums, long k) {
      // Write your code here.
    }

}
Checking account…