Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

A variation of 'maximum sum of subarray' - using hashmap

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int c0 = 0, c1 = 0;
        int r = 0;
        unordered_map<int, int> hm;
        for(int i = 0; i < nums.size(); i ++)
        {
            c0 += !nums[i];
            c1 += nums[i];
            int d = c0 - c1;
            if(d == 0)
            {
                r = max(r, i + 1);
            }
            else
            {
                bool bFound = hm.find(-d) != hm.end();
                if(bFound) r = max(r, i + 1 - hm[-d]);    
                else hm[-d] = i + 1;
            }
        }
        return r;
    }
};
posted on 2017-02-27 11:30  Tonix  阅读(114)  评论(0)    收藏  举报