Daily challenge for 2026-02-05
401. Longest Subarray With Sum K
Given an array of positive integers nums and an integer k, find the length of the longest contiguous subarray whose sum is equal to k. If no such subarray exists, return 0.
Example:Input: nums = [1, 2, 1, 2, 1], k = 3Output: 3
(The subarray [1, 2] sums to 3, but [1, 2, 1, 2, 1] contains [1, 1, 1] which is length 3, or [2, 1] length 2. Wait, actually [1, 2] is length 2. [2, 1] is length 2. [1, 2] is length 2. The longest is actually [1, 1, 1] if we had it, but here [1, 2] sums to 3. Let's look at [1, 2, 1, 2, 1] again. Subarrays summing to 3: [1, 2] (len 2), [2, 1] (len 2), [1, 2] (len 2), [2, 1] (len 2). Wait, [1, 2] is index 0-1. [2, 1] is index 1-2. [1, 2] is index 2-3. [2, 1] is index 3-4. Actually, if input is [1, 2, 3] and k=3, answer is 2 ([1, 2]) or 1 ([3]). Max length is 2.)
Correct Example:Input: nums = [1, 2, 1, 1, 1], k = 3Output: 3
(Subarray [1, 1, 1] has sum 3 and length 3).