LeetCode-Maximum Size Subarray Sum Equals k

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.

Example 1:

Given nums = [1, -1, 5, -2, 3], k = 3,
return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)

Example 2:

Given nums = [-2, -1, 2, 1], k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)

Follow Up:
Can you do it in O(n) time?

 
Analysis:
 
Use a HashMap to store pair of <sum val, ind>, then for each sum[i], we query whether there is <sum[i]-k, x>, if yes, then we found one candidate.
 
Solution:
 1 public class Solution {
 2     public int maxSubArrayLen(int[] nums, int k) {
 3         int res = 0, len = nums.length;
 4         Map<Integer,Integer> sumMap = new HashMap<Integer,Integer>();        
 5 
 6         int sum=0;
 7         for (int i=0;i<len;i++){
 8             sum += nums[i];
 9             if (sum==k) {
10                 res = i+1;
11             } else if (sumMap.containsKey(sum-k)){
12                 res = Math.max(res, i-sumMap.get(sum-k));
13             }
14             if (!sumMap.containsKey(sum)){
15                 sumMap.put(sum,i);
16             }    
17         }
18 
19         return res;
20     }
21 }

 

posted @ 2016-08-12 12:24  LiBlog  阅读(180)  评论(0编辑  收藏  举报