MrainW's Home

All things come to those who wait!

0%

LeetCode 525. Contiguous Array

Question

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.

https://leetcode.com/problems/contiguous-array/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int findMaxLength(int[] nums) {
for (int i = 0; i < nums.length; i++) if (nums[i] == 0) nums[i] = -1;
int res = 0, sum = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
for (int i = 0; i < nums.length; i++){
sum += nums[i];
if (map.containsKey(sum)) res = Math.max(res, i - map.get(sum));
else map.put(sum, i);
}
return res;
}
}

Complexity:

Time complexity: O( n)

Space complexity: O(n)

Welcome to my other publishing channels