码迷,mamicode.com
首页 > 其他好文 > 详细

[?]*Maximum Size Subarray Sum Equals k

时间:2016-01-12 07:43:37      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

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?

public int maxSubArrayLen(int[] nums, int k) {
    int sum = 0, max = 0;
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < nums.length; i++) {
        sum = sum + nums[i];
        if (sum == k) max = i + 1;
        else if (map.containsKey(sum - k)) max = Math.max(max, i - map.get(sum - k));
        if (!map.containsKey(sum)) map.put(sum, i);
    }
    return max;
}

 

[?]*Maximum Size Subarray Sum Equals k

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5123140.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!