325. Maximum Size Subarray Sum Equals k

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

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

Example 1:

Input: nums = [1, -1, 5, -2, 3], k = 3
Output: 4 
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.

Example 2:

Input: nums = [-2, -1, 2, 1], k = 1
Output: 2 
Explanation: The subarray [-1, 2] sums to 1 and is the longest.

Hint:

  1. Try to compute a sum of a subsequence very fast, i.e in O(1) … Think of prefix sum array.
  2. Given S[i] a partial sum that starts at position 0 and ends at i, what can S[i - k] tell you ?
  3. Use HashMap + prefix sum array

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

方法0:

方法1: hash + prefix

思路:

根据hint,可以套用560. Subarray Sum Equals K中的方法。从前往后遍历一遍,对于每一个数字nums[i],记录前缀和prefix[i],并且向前查找hash中有没有prefix[i] - k。这里需要用到的是前面prefix[i] - k 所对应的entry,并且只用取最小的一个,因为遍历顺序的关系,累计长度一定不会超过前面的位置。那么需要的数据结构就是unordered_map<int, int>。 如果该entry已经存在,可以跳过,不存在则记录下来,也就是第一次出现的位置。

易错点

  1. 不管sum是否已经存在在hash中,result = max(result, i - prefix[sum - k])都应该参与计算结果。当前位置不加入hash只是因为它不会再成为后面的起点,但是有可能作为终点和前面组成最长subarray。不要直接跳过。
  2. 还要检查prefix[sum - k] 是否存在,没有这个检查不会报key error,只会返回0
  3. 两个boundary检查只用一个就行
class Solution {
public:
    int maxSubArrayLen(vector<int>& nums, int k) {
        unordered_map<int, int> prefix;
        // boundary 1
        // prefix[0] = -1;
        int result = 0;
        int sum = 0;
        for (int i = 0; i < nums.size(); i ++){
            sum += nums[i];
            // boundary 2
            if (sum == k) result = i + 1;
            else if (prefix.count(sum - k)){
                result = max(result, i - prefix[sum - k] );
            }
            if (prefix.count(sum) == 0 ){
                prefix[sum] = i;
            }
        }
        return result;
    }
};

// [1,-1,5,-2,3]
// k = 3

// sum = 3
// result = 4
// i = 3
// prefix = {0: 0, 1: 0, 5: 2, 3: 3, 6: 4}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值