Maximum Size Subarray Sum Equals k

https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/?tab=Description

非sorted的subarray、window题目,用的subsum解法;

class Solution {
public:
    int maxSubArrayLen(vector<int>& nums, int k) {
        int sum  = 0;
        int n = nums.size();
        map<int, int> hash;
        hash[0] = 0;
        int ret = 0;

        for(int i = 0; i<n; i++)
        {
            sum = sum + nums[i];
            int target = sum - k;
            if(hash.find(target) != hash.end())
            {
                ret = max(ret, i-hash[target]+1);
            }

            if(hash.find(sum) == hash.end())
            {
                hash[sum] = i+1;
            }
        }

        return ret;

    }
};

results matching ""

    No results matching ""