Skip to content

Commit 80ec484

Browse files
committed
maximum product subarray solution
1 parent 7bc75e5 commit 80ec484

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var maxProduct = function (nums) {
6+
// μ΅œλŒ€ 곱을 μ €μž₯ν•  λ³€μˆ˜
7+
let maxProduct = nums[0];
8+
// ν˜„μž¬ μœ„μΉ˜κΉŒμ§€μ˜ μ΅œλŒ€ κ³±κ³Ό μ΅œμ†Œ 곱을 μ €μž₯ν•  λ³€μˆ˜
9+
let currentMax = nums[0];
10+
let currentMin = nums[0];
11+
12+
// λ°°μ—΄μ˜ 두 번째 μ›μ†ŒλΆ€ν„° 순회
13+
for (let i = 1; i < nums.length; i++) {
14+
const num = nums[i];
15+
16+
// 음수λ₯Ό κ³±ν•  경우 μ΅œλŒ€μ™€ μ΅œμ†Œκ°€ λ°”λ€” 수 μžˆμœΌλ―€λ‘œ 미리 μ €μž₯
17+
const tempMax = currentMax;
18+
19+
// ν˜„μž¬ μˆ«μžμ™€ κ³±ν–ˆμ„ λ•Œμ˜ μ΅œλŒ€/μ΅œμ†Œ 값을 계산
20+
currentMax = Math.max(num, num * currentMax, num * currentMin);
21+
currentMin = Math.min(num, num * tempMax, num * currentMin);
22+
23+
// 전체 μ΅œλŒ€ 곱을 μ—…λ°μ΄νŠΈ
24+
maxProduct = Math.max(maxProduct, currentMax);
25+
}
26+
27+
return maxProduct;
28+
};

0 commit comments

Comments
Β (0)