Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 2286ca9

Browse files
committedSep 6, 2024Β·
5. Maximum Product Subarray
1 parent d0efeef commit 2286ca9

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
 
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
* 쑰건
3+
* κ°€μž₯ 큰 λ°°μ—΄ 곱을 μ°Ύμ•„μ„œ return
4+
* 32-bit integer
5+
* -10<=num[i]<=10
6+
7+
* 아이디어
8+
* 이전 μ΅œλŒ€κ°’, μ΅œμ†Œκ°’μ„ ꡬ해둔닀
9+
* μ΅œλŒ€κ³±μ΄ λ‚˜μ˜¬ 수 μžˆλŠ” 경우
10+
* 1) μ΅œμ†Œκ°’ κ³±ν•œκ²ƒ(-*-)
11+
* 2) μ΅œλŒ€κ°’ κ³±ν•œκ²ƒ(+*+)
12+
* 3) μžκΈ°μžμ‹ μΈ 경우(+)
13+
* 배열을 λŒλ©΄μ„œ μ„Έ κ°€μ§€ 쀑 μ΅œλŒ€μ΅œμ†Œκ°’μ„ κ°±μ‹ ν•΄λ‚˜κ°„λ‹€
14+
*
15+
*/
16+
function maxProduct(nums: number[]): number {
17+
let max = nums[0];
18+
let min = nums[0];
19+
let result = nums[0];
20+
21+
for (let i = 1; i < nums.length; i++) {
22+
const candidates = [nums[i] * max, nums[i], nums[i] * min];
23+
let currMax = Math.max(...candidates);
24+
let currMin = Math.min(...candidates);
25+
26+
max = currMax;
27+
min = currMin;
28+
29+
result = Math.max(currMax, result);
30+
}
31+
return result;
32+
}
33+
34+
// TC: O(n)
35+
// SC: O(1)

0 commit comments

Comments
 (0)
Please sign in to comment.