Maximum Length of Subarray With Positive Product LeetCode solution in JavaScript

1
/**
2
* @param {number[]} nums
3
* @return {number}
4
*/
5
var getMaxLen = function (nums) {
6
let leftToRight = 0,
7
p = 1,
8
count = 0,
9
max = 0,
10
item;
11
//Process elements from left to right
12
for (let i = 0; i < nums.length; i++) {
13
if (nums[i] === 0) {
14
p = 0;
15
} else if (nums[i] > 0) {
16
p *= 1;
17
} else if (nums[i] < 0) {
18
p *= -1;
19
}
20
count++;
21
if (p > 0) {
22
max = Math.max(max, count);
23
}
24
if (p === 0) {
25
p = 1;
26
count = 0;
27
}
28
}
29
count = 0;
30
p = 1;
31
//Process elements from right to left
32
for (let i = nums.length - 1; i >= 0; i--) {
33
if (nums[i] === 0) {
34
p = 0;
35
} else if (nums[i] > 0) {
36
p *= 1;
37
} else if (nums[i] < 0) {
38
p *= -1;
39
}
40
count++;
41
if (p > 0) {
42
max = Math.max(max, count);
43
}
44
if (p === 0) {
45
p = 1;
46
count = 0;
47
}
48
}
49
return max;
50
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0