Skip to content

Commit 08e7b1d

Browse files
committed
solve: Maximum Product Subarray
1 parent 6d45f22 commit 08e7b1d

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
Constraints:
3+
- 1 <= nums.length <= 2 * 10^4
4+
- -10 <= nums[i] <= 10
5+
- The product of any subarray of nums is guaranteed to fit in a 32-bit integer.
6+
7+
Time Complexity:
8+
- O(n): ๋ฐฐ์—ด์„ ํ•œ ๋ฒˆ๋งŒ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ฐ ์œ„์น˜์—์„œ ์ƒ์ˆ˜ ์‹œ๊ฐ„ ์—ฐ์‚ฐ๋งŒ ์ˆ˜ํ–‰
9+
10+
Space Complexity:
11+
- O(1): ๊ณ ์ •๋œ ์ถ”๊ฐ€ ๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉ (curr_max, curr_min, ...)
12+
13+
ํ’€์ด๋ฐฉ๋ฒ•:
14+
1. DP๋กœ ๊ฐ ์œ„์น˜์—์„œ ๊ฐ€๋Šฅํ•œ ์ตœ๋Œ€๊ณฑ๊ณผ ์ตœ์†Œ๊ณฑ์„ ๋™์‹œ์— ์ถ”์ ํ•จ
15+
2. ๊ฐ ์œ„์น˜์—์„œ ์„ธ ๊ฐœ์˜ ์„ ํƒ์ง€ ์กด์žฌ: ์ƒˆ๋กœ ์‹œ์ž‘ vs ์ด์ „ ์ตœ๋Œ€๊ณฑ๊ณผ ๊ณฑํ•˜๊ธฐ vs ์ด์ „ ์ตœ์†Œ๊ณฑ๊ณผ ๊ณฑํ•˜๊ธฐ
16+
3. ์ตœ์†Œ๊ณฑ์ด ํ•„์š”ํ•œ ์ด์œ : ๋‚˜์ค‘์— ์Œ์ˆ˜๋ฅผ ๋งŒ๋‚ฌ์„ ๋•Œ ์ตœ๋Œ€๊ฐ’์ด ๋  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ
17+
4. ๋งค ๋‹จ๊ณ„๋งˆ๋‹ค result ์—…๋ฐ์ดํŠธ
18+
19+
๊ณ ๋ ค์‚ฌํ•ญ:
20+
1. ๊ฐ’์ด 0์ธ ๊ฒฝ์šฐ โ†’ ์ƒˆ๋กœ ์‹œ์ž‘ํ•ด์•ผ ํ•จ
21+
2. temp ๋ณ€์ˆ˜: curr_max๋ฅผ ์—…๋ฐ์ดํŠธํ•˜๋ฉด curr_min ๊ณ„์‚ฐ ์‹œ ์›๋ž˜ ๊ฐ’์ด ํ•„์š”ํ•จ
22+
"""
23+
class Solution:
24+
def maxProduct(self, nums: List[int]) -> int:
25+
curr_max = nums[0]
26+
curr_min = nums[0]
27+
result = nums[0]
28+
29+
for i in range(1, len(nums)):
30+
temp = curr_max
31+
curr_max = max(nums[i], curr_max * nums[i], curr_min * nums[i])
32+
curr_min = min(nums[i], temp * nums[i], curr_min * nums[i])
33+
result = max(result, curr_max)
34+
35+
return result
36+
37+
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
"""
2+
Constraints:
3+
-
4+
5+
Time Complexity:
6+
-
7+
8+
Space Complexity:
9+
-
10+
11+
ํ’€์ด๋ฐฉ๋ฒ•:
12+
1.
13+
"""
14+

0 commit comments

Comments
ย (0)