Skip to content

Commit 918e6da

Browse files
committed
solve: maximum product subarray
1 parent 15652ff commit 918e6da

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// TC: O(N)
2+
// SC: O(1)
3+
4+
/**
5+
* @param {number[]} nums
6+
* @return {number}
7+
*/
8+
var maxProduct = function (nums) {
9+
let maximumProduct = Number.MIN_SAFE_INTEGER;
10+
let subProduct = 1;
11+
// 1. μ’Œμ—μ„œ 우둜 λˆ„μ κ³±μ„ μ €μž₯ν•˜κΈ° μœ„ν•΄ 순회
12+
for (let index = 0; index < nums.length; index++) {
13+
// 2. 0을 λ§Œλ‚˜λ©΄ λˆ„μ κ³±μ— κ³±ν•˜μ§€ μ•Šκ³  1둜 μ΄ˆκΈ°ν™”
14+
if (nums[index] === 0) {
15+
maximumProduct = Math.max(maximumProduct, 0);
16+
subProduct = 1;
17+
continue;
18+
}
19+
// 3. 맀번 λˆ„μ κ³±μ„ κ°±μ‹ 
20+
subProduct *= nums[index];
21+
maximumProduct = Math.max(maximumProduct, subProduct);
22+
}
23+
24+
subProduct = 1;
25+
// 4. μš°μ—μ„œ 쒌둜 λˆ„μ κ³±μ„ μ €μž₯ν•˜κΈ° μœ„ν•΄ 순회
26+
for (let index = nums.length - 1; index >= 0; index--) {
27+
// 5. 0을 λ§Œλ‚˜λ©΄ λˆ„μ κ³±μ— κ³±ν•˜μ§€ μ•Šκ³  1둜 μ΄ˆκΈ°ν™”
28+
if (nums[index] === 0) {
29+
maximumProduct = Math.max(maximumProduct, 0);
30+
subProduct = 1;
31+
continue;
32+
}
33+
// 6. 맀번 λˆ„μ κ³±μ„ κ°±μ‹ 
34+
subProduct *= nums[index];
35+
maximumProduct = Math.max(maximumProduct, subProduct);
36+
}
37+
38+
return maximumProduct;
39+
};

0 commit comments

Comments
Β (0)