Skip to content

Commit 187d1d2

Browse files
committed
add solution: maximum-product-subarray
1 parent 985bf23 commit 187d1d2

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'''
2+
# 152. Maximum Product Subarray
3+
4+
solution reference: https://www.algodale.com/problems/maximum-product-subarray/
5+
6+
## ์ตœ๋Œ€ ๊ณฑ ๋ฐฐ์—ด ๊ตฌํ•˜๊ธฐ
7+
- ์—ฐ์† ๋ฐฐ์—ด(subarray)์— ์–‘์ˆ˜, ์Œ์ˆ˜, 0์ด ํฌํ•จ๋  ์ˆ˜ ์žˆ๋‹ค.
8+
- ์Œ์ˆ˜๊ฐ€ ๊ฒฐ๊ณผ์— ์˜ํ–ฅ์„ ๋ฏธ์น  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ตœ์†Œ๊ฐ’/์ตœ๋Œ€๊ฐ’ ์ถ”์ ์ด ํ•„์š”ํ•˜๋‹ค.
9+
10+
## ๊ฐ’
11+
- result: ์ตœ์ข…์ ์œผ๋กœ ๋ฐ˜ํ™˜ํ•  ๊ฐ’
12+
- min_prod: ํ˜„์žฌ๊นŒ์ง€์˜ ์ตœ์†Œ ๊ณฑ ๊ฐ’ (์Œ์ˆ˜๋ฅผ ๊ณ ๋ คํ•œ ์ถ”์ )
13+
- max_prod: ํ˜„์žฌ๊นŒ์ง€์˜ ์ตœ๋Œ€ ๊ณฑ ๊ฐ’
14+
15+
## ์ƒˆ๋กœ์šด ๊ฐ’ num์ด ์ฃผ์–ด์กŒ์„ ๋•Œ
16+
- ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ์‹œ์ž‘ํ•  ์ง€, ๊ธฐ์กด ๋ฐฐ์—ด์— ์ถ”๊ฐ€ํ•  ์ง€ ๊ฒฐ์ •
17+
- ํ›„๋ณด๋“ค๋กœ ์ตœ๋Œ€๊ฐ’์˜ ๊ฐ€๋Šฅ์„ฑ์„ ํ™•์ธํ•˜๊ณ  result๋ฅผ ์—…๋ฐ์ดํŠธํ•œ๋‹ค.
18+
'''
19+
class Solution:
20+
def maxProduct(self, nums: List[int]) -> int:
21+
result = nums[0]
22+
min_prod = 1
23+
max_prod = 1
24+
25+
for num in nums:
26+
candidates = (min_prod * num, max_prod * num, num)
27+
min_prod = min(candidates)
28+
max_prod = max(candidates)
29+
result = max(max_prod, result)
30+
31+
return result

0 commit comments

Comments
ย (0)