Sponsored
Sponsored
The idea is to transform the array by converting 0s to -1s, which allows us to restate the problem as finding the longest contiguous subarray with a sum of 0. We can use a hash map to store the first occurrence of each prefix sum.
Time Complexity: O(n), where n is the length of the input array.
Space Complexity: O(n) for the hash map storage.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int FindMaxLength(int[] nums) {
6 Dictionary<int, int> countMap = new Dictionary<int, int>{{0, -1}};
7 int maxLength = 0, count = 0;
8 for (int i = 0; i < nums.Length; i++) {
9 count += nums[i] == 1 ? 1 : -1;
10 if (countMap.ContainsKey(count)) {
11 maxLength = Math.Max(maxLength, i - countMap[count]);
12 } else {
13 countMap[count] = i;
14 }
15 }
16 return maxLength;
17 }
18}
19
This C# solution uses a Dictionary to register the first place each net count value appears during a single loop over the array. We adjust the counts for 0s and 1s and use this to determine the valid subarray length.
This simple approach checks every possible subarray and calculates its sum, verifying if it has an equal number of 0s and 1s. This method, while simple, serves as an exercise in understanding the problem better prior to using an optimized solution.
Time Complexity: O(n^2)
Space Complexity: O(1), as we do not use extra space other than primitive variables.
1public class Solution {
public int FindMaxLength(int[] nums) {
int maxLength = 0;
for (int start = 0; start < nums.Length; start++) {
int count0 = 0, count1 = 0;
for (int end = start; end < nums.Length; end++) {
if (nums[end] == 0) count0++;
else count1++;
if (count0 == count1) {
maxLength = Math.Max(maxLength, end - start + 1);
}
}
}
return maxLength;
}
}
This C# brute force option methodically tests each range of elements possible in the array, adjusting the leading maximum possible length each period the balance (0s and 1s) occurs.