Skip to content

Commit 0bd99fe

Browse files
committed
add solution : 152. Maximum Product Subarray
1 parent 58fd46f commit 0bd99fe

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

β€Žmaximum-product-subarray/mmyeon.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @link https://leetcode.com/problems/maximum-product-subarray/
3+
*
4+
* μ ‘κ·Ό 방법 :
5+
* - μŒμˆ˜κ°€ 짝수번 λ‚˜μ˜€λ©΄ μ΅œλŒ€κ°’μ΄ 될 수 μžˆμœΌλ‹ˆκΉŒ μ΅œμ†Œκ³±, μ΅œλŒ€κ³±μ„ λͺ¨λ‘ μ—…λ°μ΄νŠΈ
6+
* - ν˜„μž¬ 값이 λ‹¨λ…μœΌλ‘œ μ΅œμ†Œ, μ΅œλŒ€μΌ 수 μžˆμœΌλ‹ˆκΉŒ ν˜„μž¬κ°’, μ΅œμ†Œκ³± * ν˜„μž¬κ°’, μ΅œλŒ€κ³± * ν˜„μž¬κ°’μ„ 비ꡐ
7+
*
8+
* μ‹œκ°„λ³΅μž‘λ„ : O(n)
9+
* - nums 1회 순회
10+
*
11+
* κ³΅κ°„λ³΅μž‘λ„ : O(1)
12+
* - κ³ μ •λœ λ³€μˆ˜λ§Œ μ‚¬μš©
13+
*/
14+
function maxProduct(nums: number[]): number {
15+
let currentMin = nums[0],
16+
currentMax = nums[0],
17+
maxSoFar = nums[0];
18+
19+
for (let i = 1; i < nums.length; i++) {
20+
const num = nums[i];
21+
const minCandidate = currentMin * num;
22+
const maxCandidate = currentMax * num;
23+
24+
currentMin = Math.min(num, minCandidate, maxCandidate);
25+
currentMax = Math.max(num, minCandidate, maxCandidate);
26+
27+
maxSoFar = Math.max(currentMax, maxSoFar);
28+
}
29+
30+
return maxSoFar;
31+
}

0 commit comments

Comments
Β (0)