O(n) hash unordered map concise and clean C++ solution


  • 0
    W
    class Solution {
    public:
        int maxSubArrayLen(vector<int>& nums, int k) {
            unordered_map<int,int> M;
            int max_k = 0;
            for(int i=0, s = 0; i<nums.size(); ++i){
                s += nums[i];
                if(M.find(s) == M.end())
                    M[s] = i;
                if(M.find(s-k) != M.end())
                    max_k = max(max_k, i-M[s-k]);
                if(s == k)
                    max_k = max(max_k, i+1);
            }
            return max_k;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.