Menu
CoddyTech

Longest Subarray with Sum K

Given the integers nums and a target k, return the length of the longest subarray whose elements total exactly k. A subarray is a stretch of consecutive elements, at least one long. Some values may be zero or below zero. If no subarray adds up to k, return 0.

Function

longestSubarrayWithSumK(nums: integer-array, k: integer) → integer
numsinteger-array
the integers to search, negatives and zeros included
kinteger
the exact sum the subarray must have
Returnsinteger
the length of the longest subarray that adds up to k, or 0 when none does

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • -104 ≤ nums[i] ≤ 104
  • -109 ≤ k ≤ 109
  • Every prefix sum stays between -2 × 108 and 2 × 108, so 32-bit integers are enough.
  • Return 0 when no subarray adds up to k.

Examples

Input
nums = [2, -1, 3, 1, -4, 2, 3]k = 5
Output
5
Explanation
Three runs add up to 5: [2, 3] at the end, [2, -1, 3, 1] at the start, and [3, 1, -4, 2, 3] at indices 2 to 6. The last is the longest, with 5 elements.
challenge icon

Follow-up

How would you find the longest subarray whose sum is at most k, with negative values still allowed?

Reset code
def longestSubarrayWithSumK(nums, k):
    # Write code here

Test #1

Test #2

Test #3

Arguments

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

Expected Output

5