To solve the problem of finding the longest subarray with a given sum k
, we can take advantage of a technique called the sliding window. This approach works efficiently when all elements in the array are positive.
Understanding the Goal
We need to find a sequence of contiguous elements (a subarray) in the array that adds up exactly to k
. But among all such valid subarrays, we're interested in the one with the maximum length.
Why Sliding Window Works Here
Since all numbers are positive, the sum of a subarray can only increase if we add more elements. If at any point the current sum becomes greater than k
, we know we need to shrink the window from the left to try reducing the sum.
How We Approach It
- We start with two pointers:
start
and end
, both at index 0 initially.
- We also maintain a
curr_sum
variable to store the current subarray sum, and max_len
to track the maximum length found.
- As we move the
end
pointer through the array:
- We add the current element to
curr_sum
.
- If
curr_sum
becomes greater than k
, we move the start pointer right, subtracting those values from curr_sum
, until it is ≤ k
.
- If
curr_sum == k
, we calculate the window length (end - start + 1
) and update max_len
if it's larger than before.
What Happens in Special Cases?
- No matching subarray: If no window ever sums to
k
, max_len
remains 0.
- Empty array: There's no subarray to check, so return 0.
- Single element equals k: Then max_len is 1.
- Target sum is 0: Since all elements are positive, we can't reach 0, so return 0.
Conclusion
This method is optimal and runs in linear time O(n)
since each element is visited at most twice (once by end, once by start). It works beautifully for arrays with only positive numbers.