Skip to content

Commit 7a2d509

Browse files
committed
Added DP approach
1 parent 0f4e7cd commit 7a2d509

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

maximum-product-subarray/kimyoung.js

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,20 @@ var maxProduct = function (nums) { // brute force approach - doesn't pass leetco
99
return maxProduct;
1010
};
1111

12-
// time - O(n^2) double for loop
13-
// space - O(n^2) total count of subarrays = n*(n+1)/2
12+
// time - O(n^3) double for loop * reduce()
13+
// space - O(1)
1414

15+
var maxProduct = function (nums) { // DP approach
16+
let result = nums[0];
17+
let [min, max] = [1, 1];
1518

16-
// TODO - different approach
19+
for (const num of nums) {
20+
[min, max] = [Math.min(num * min, num * max, num), Math.max(num * min, num * max, num)];
21+
result = Math.max(max, result);
22+
}
23+
24+
return result;
25+
};
26+
27+
// time - O(n) looping through nums once
28+
// space - O(1) extra memory irrelevant to input

0 commit comments

Comments
 (0)