Skip to content

Commit 2e26787

Browse files
committed
maximum-product-subarray solution
1 parent b0b8657 commit 2e26787

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution:
2+
def maxProduct(self, nums: List[int]) -> int:
3+
4+
# ์—ฐ์†๋œ ๋ถ€๋ถ„ ๋ฐฐ์—ด์˜ ๊ณฑ์ด ๊ฐ€์žฅ ํฐ ๊ฐ’ ์ฐพ๊ธฐ(์ •์ˆ˜)
5+
# DP (์‹œ๊ฐ„๋ณต์žก๋„ O(n), ๊ณต๊ฐ„๋ณต์žก๋„ O(1))
6+
answer = nums[0]
7+
prev_max = prev_min = nums[0]
8+
9+
for i in range(1,len(nums)):
10+
n = nums[i]
11+
12+
# ์Œ์ˆ˜*์Œ์ˆ˜๋Š” ์–‘์ˆ˜์ด๋ฏ€๋กœ max,min ๋‘˜๋‹ค ๊ณ„์‚ฐ
13+
curr_max = max(n,prev_max*n, prev_min*n)
14+
curr_min = min(n,prev_max*n, prev_min*n)
15+
16+
answer = max(answer, curr_max) # ์ตœ๋Œ€ ๊ณฑ ์—…๋ฐ์ดํŠธ
17+
prev_max, prev_min = curr_max, curr_min # ํ˜„์žฌ๊ฐ’์„ ์ด์ „๊ฐ’์œผ๋กœ ์—…๋ฐ์ดํŠธ
18+
19+
return answer

0 commit comments

Comments
ย (0)