-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0525-contiguous-array.js
More file actions
36 lines (31 loc) · 905 Bytes
/
0525-contiguous-array.js
File metadata and controls
36 lines (31 loc) · 905 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Contiguous Array
* Time Complexity: O(nums.length)
* Space Complexity: O(nums.length)
*/
var findMaxLength = function (nums) {
const balanceTracker = new Map();
balanceTracker.set(0, -1);
let maxOverallLength = 0;
let runningSumValue = 0;
for (
let currentElementIndex = 0;
currentElementIndex < nums.length;
currentElementIndex++
) {
const valueFromNums = nums[currentElementIndex];
if (valueFromNums === 1) {
runningSumValue++;
} else {
runningSumValue--;
}
if (balanceTracker.has(runningSumValue)) {
const priorIndex = balanceTracker.get(runningSumValue);
const potentialCandidateLength = currentElementIndex - priorIndex;
maxOverallLength = Math.max(maxOverallLength, potentialCandidateLength);
} else {
balanceTracker.set(runningSumValue, currentElementIndex);
}
}
return maxOverallLength;
};