c++ solution with O(n)


  • 0
    B
    class Solution {
    public:
        int findMaxLength(vector<int>& nums) {
            map<int, int> diffMap;
            diffMap[0] = -1;
            int maxLen = 0;
            int one = 0;
            int zero = 0;
            for(int i = 0; i < nums.size(); i++){
                if(nums[i] == 0) one++;
                if(nums[i] == 1) zero++;
                int diff = one - zero;
                if(diffMap.find(diff) != diffMap.end()){
                    maxLen = max(i - diffMap[diff], maxLen);
                }
                else diffMap[diff] = i;
            }
            return maxLen;
        }
    };
    

Log in to reply
 

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