Link to the problem
The problem is here: https://leetcode-cn.com/problems/contiguous-array/
Problem description
Given a binary array nums which consists of only 0 and 1, find the length of the longest subarray of nums that has the equal number of 0’s and 1’s.
Idea
To simplify the problem, we set all 0’s in nums to be -1. Then the problem becomes: find the length of the longest subarray of nums that sums up to 0.
It can be solved by using the prefix-sum algorithm. We define , and for simplicity,
. The problem is to find with
and
.
Implementation
My implementation is this:
int findMaxLength(vector<int>& nums) {unordered_map<int, int> mp;mp[0] = -1;int sum = 0, ans = 0;for (int i = 0; i < nums.size(); i++) {if (nums[i]) {sum++;} else {sum--;}auto it = mp.find(sum);if (it != mp.end()) {ans = max(ans, i - it->second);} else {mp.insert({sum, i});}}return ans;}
Note:
- Do not need to convert 0 to -1 actually. Just use a variable to record the running sum.
- Should only keep the position of the first occurrence of some sum because we are finding the longest subarray.
