Posted on

Description

Submission

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        unordered_map<int, int> sumIndex{{0, -1}};

        int sum = 0, ret = 0;
        for(int i = 0; i < nums.size(); ++i) {
            if(nums[i] == 0) {
                sum--;
            } else {
                sum++;
            }

            if(sumIndex.find(sum) == sumIndex.end()) {
                sumIndex[sum] = i;
            } else {
                ret = max(ret, i - sumIndex[sum]);
            }
        }

        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *