Skip to content

Commit b5bce25

Browse files
committed
Add week 4 solutions: maximum-product-subarray
1 parent a542643 commit b5bce25

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

maximum-product-subarray/gitsunmin.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* https://leetcode.com/problems/maximum-product-subarray
3+
* time complexity : O(n)
4+
* space complexity : O(1)
5+
*/
6+
function maxProduct(nums: number[]): number {
7+
let r = nums[0];
8+
let mx = 1, mn = 1;
9+
10+
for (let i = 0; i < nums.length; i++) {
11+
const tempMx = mx * nums[i];
12+
const tempMn = mn * nums[i];
13+
14+
mx = Math.max(tempMx, tempMn, nums[i]);
15+
mn = Math.min(tempMx, tempMn, nums[i]);
16+
17+
r = Math.max(r, mx);
18+
}
19+
20+
return r;
21+
}

0 commit comments

Comments
 (0)