10 lines C++ O(n)


  • 0
    class Solution {
    public:
        int maxSubArrayLen(vector<int>& nums, int k) {
            unordered_map<int, int>m;
            int sum = 0;
            int maxlen = 0;
            for(int i = 0; i < nums.size(); i++){
                sum += nums[i];
                if(!m.count(sum)) m[sum] = i;
                if(sum == k) maxlen = i + 1;
                else if(m.count(sum - k) > 0) maxlen = max(maxlen, i - m[sum - k]);
            }
            return maxlen;
        }
    };
    

Log in to reply
 

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