Leetcode 325 Solution

This article provides solution to leetcode question 325 (maximum-size-subarray-sum-equals-k)

https://leetcode.com/problems/maximum-size-subarray-sum-equals-k

Solution

class Solution {
public:
    int maxSubArrayLen(vector<int>& nums, int k) {
        unordered_map<int, int> s;
        s[0] = -1;
        int sum = 0;
        int res = 0;

        for (int i = 0; i < nums.size(); i++)
        {
            sum += nums[i];

            if (s.find(sum) == s.end())
                s[sum] = i;

            if (s.find(sum - k) != s.end())
                res = max(res, i - s[sum - k]);
        }

        return res;
    }
};