Design Gurus Logo
Maximum Size Subarray Sum Equals k (medium)

Problem Statement

Given an array of integers nums and an integer k, find the length of the longest subarray that sums to k. If no such subarray exists, return 0.

Examples

Example 1:

  • Input: nums = [1, 2, 3, -2, 5], k = 5
  • Output: 2
  • Explanation: The longest subarray with a sum of 5 is [2, 3], which has a length of 2.

Example 2:

  • Input: nums = [-2, -1, 2, 1], k = 1
  • Output: 2
  • Explanation: The longest subarray with a sum of 1 is [-1, 2], which has a length of 2.

Example 3:

  • Input: nums = [3, 4, 7, 2, -3, 1, 4, 2], k = 7
  • Output: 4
  • Explanation: The longest subarray with a sum of 7 is [7, 2, -3, 1], which has a length of 4.

Constraints:

  • 1 <= nums.length <= 2 * 10<sup>5</sup>
  • -10<sup>4</sup> <= nums[i] <= 10<sup>4</sup>
  • -10<sup>9</sup> <= k <= 10<sup>9</sup>

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory