LintCode 911: Maximum Size Subarray Sum Equals k

911. 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

Example1

Input:  nums = [1, -1, 5, -2, 3], k = 3

Output: 4

Explanation:

because the subarray [1, -1, 5, -2] sums to 3 and is the longest.

Example2

Input: nums = [-2, -1, 2, 1], k = 1

Output: 2

Explanation:

because the subarray [-1, 2] sums to 1 and is the longest.

Challenge

Can you do it in O(n) time?

Notice

The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.

解法1:presums + hashmap

先构建presums数组,然后就可以转换成一个数组里面找两个数之差等于k的问题了。

这个问题可以用同向双指针,也可以用hashmap。

注意,我们要考虑某个数本身就是k和某个presum本身就是k这两种特殊情况,因为presums里面两个元素相减的差并不会考虑头一个元素,所以会漏掉presum的情况。

class Solution {
public:
    /**
     * @param nums: an array
     * @param k: a target value
     * @return: the maximum length of a subarray that sums to k
     */
    int maxSubArrayLen(vector<int> &nums, int k) {
        int n = nums.size();
        if (n == 0) return 0;
        vector<int> presums(n);
        int maxLen = 0;
        
        presums[0] = nums[0];
        if (nums[0] == k) maxLen = 1;
        for (int i = 1; i < n; ++i) {
            presums[i] = presums[i - 1] + nums[i];
            if (nums[i] == k) maxLen = max(maxLen, 1);
            if (presums[i] == k) maxLen = max(maxLen, i + 1);
        }
        unordered_map<int, int> hashMap; //value, index
        for (int i = 0; i < n; ++i) {
            int temp = presums[i] - k;
            if (hashMap.find(temp) != hashMap.end()) {
                maxLen = max(maxLen, i - hashMap[temp]);
            }
            if (hashMap.find(presums[i]) == hashMap.end()) hashMap[presums[i]] = i;
        }

        return maxLen;
    }
};

解法2:presumes + two pointer (同向)

注意!这题不能用同向双指针(滑动窗口)!因为测试用例里面有负数!下面这个链接讲的很好。
算法学习-滑动窗口_滑动窗口处理-CSDN博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值