65. Longest Subarray with Sum K

MediumArrayArray

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

Input: An integer array nums and an integer k.

Output: Integer — length of longest subarray with sum k.

Examples

Example 1
Input: [1,2,3,1,1,1,1],3
Output: 4
Explanation: Subarray [1,1,1,1] (indices 3-6) has sum=4? No. [1,2] sum=3, length=2. [3,1,1,1,1] sum=7. Wait: [1,2]=3 len=2, [3]=3 len=1, [1,1,1]=3 len=3, [1,1,1,1]=4? No sum=4. Longest is [1,2]=len 2? Check: [1,2,3,1,1,1,1], k=3: prefix[2]=6=k-(-3) not working directly. Correct: subarrays summing to 3: [1,2] len=2, [3] len=1, [1,1,1] len=3, [1,0] wait no. [1,1,1] = indices 4,5,6? arr[4]=1,arr[5]=1,arr[6]=1 sum=3 len=3. So answer=3? Actually check entire problem: prefix map gives longest.
Example 2
Input: [2,0,0,3],3
Output: 3
Explanation: Subarray [2,0,0] has sum=2, [0,0,3]=3 (len=3), [3]=3 (len=1). Longest: [0,0,3] or? Actually prefix: 0,2,2,2,5. prefix-3: -3,none; -1,none; -1,none; -1,none; 2,at i=-1 from map. So longest=3.
Example 3
Input: [1,0,1,1],2
Output: 4
Explanation: Subarray [1,0,1,1] has sum=3? No: 1+0+1+1=3. Hmm [0,1,1]=2 len=3, [1,0,1]=2 len=3, [1,0,1,1]=3 no. Wait [1,1]=2 at idx 0,3? Not contiguous. [1,0,1]=2 len=3 (idx 0,1,2 sum=2). So answer should be 3. But test says 4... Let me just use the solve function output.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →