Skip to content

Commit 424e01f

Browse files
authored
Update 152-maximum-product-subarray.js
1 parent 5a02af8 commit 424e01f

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

152-maximum-product-subarray.js

+29
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,32 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const maxProduct = function(nums) {
6+
let A = nums
7+
let r = A[0];
8+
9+
// imax/imin stores the max/min product of
10+
// subarray that ends with the current number A[i]
11+
for (let i = 1, imax = r, imin = r, n = A.length; i < n; i++) {
12+
if (A[i] < 0) {
13+
let tmp = imax
14+
imax = imin
15+
imin = tmp
16+
};
17+
// max/min product for the current number is either the current number itself
18+
// or the max/min by the previous number times the current one
19+
imax = Math.max(A[i], imax * A[i]);
20+
imin = Math.min(A[i], imin * A[i]);
21+
22+
// the newly computed max value is a candidate for our global result
23+
r = Math.max(r, imax);
24+
}
25+
return r;
26+
};
27+
28+
// another
29+
130
/**
231
* @param {number[]} nums
332
* @return {number}

0 commit comments

Comments
 (0)