algoblazerEarly Access
LearnProblemsLeaderboard
Log inSign up

All problems

‹ Back to map
2 shown · 0/261 solved

Longest Subarray With Sum At Most K

GoldCommunity Beta
Asked atGoogle
Solve problem →
2000ms256MBAdded Sep 1, 2026

You are given an integer array nums (which may contain negative values) and an integer k.

Return the length of the longest contiguous subarray whose element sum is at most k. If no non-empty subarray has a sum of at most k, return 0.

Examples

Example 1

Input: nums = [3, -2, 5, -1, 4], k = 6
Output: 4
Explanation: [3, -2, 5, -1] sums to 5 <= 6 and has length 4. The whole array sums to 9 > 6.

Example 2

Input: nums = [5, 6, 7], k = 4
Output: 0
Explanation: Every element already exceeds 4, so no subarray qualifies.

Example 3

Input: nums = [1, 2, 3, 4], k = 100
Output: 4
Explanation: The whole array sums to 10 <= 100.

Constraints

  • 1≤1 \leq1≤ nums.length ≤105\leq 10^5≤105
  • −104≤-10^4 \leq−104≤ nums[i] ≤104\leq 10^4≤104
  • −109≤k≤109-10^9 \leq k \leq 10^9−109≤k≤109

Details

Solved by2 people
Time limit2000ms
Memory256MB
AddedSep 1, 202610 days ago