Skip to content

Commit df20a1b

Browse files
Create taurus09318976.py
1 parent 026942e commit df20a1b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
'''
2+
문제의 μ˜λ„
3+
이 λ¬Έμ œλŠ” λ°°μ—΄μ—μ„œ μ—°μ†λœ λΆ€λΆ„ λ°°μ—΄μ˜ 곱이 μ΅œλŒ€κ°€ λ˜λŠ” 값을 μ°ΎλŠ” λ¬Έμ œμž„.
4+
μŒμˆ˜κ°€ 있기 λ•Œλ¬Έμ— λ‹¨μˆœνžˆ μ΅œλŒ€κ°’λ§Œ μΆ”μ ν•˜λ©΄ μ•ˆ 되고, λ™μ‹œμ— μ΅œμ†Œκ°’λ„ 좔적해야 함.
5+
6+
핡심 포인트
7+
음수 Γ— 음수 = μ–‘μˆ˜ (큰 μ–‘μˆ˜κ°€ 될 수 있음)
8+
음수 Γ— μ–‘μˆ˜ = 음수 (μž‘μ•„μ§)
9+
0이 있으면 곱이 0이 됨
10+
11+
ν•΄κ²° 방법
12+
동적 ν”„λ‘œκ·Έλž˜λ°μ„ μ‚¬μš©ν•˜λ˜, μ΅œλŒ€κ°’κ³Ό μ΅œμ†Œκ°’μ„ λ™μ‹œμ— 좔적:
13+
14+
μ΅œλŒ€κ°’: μ–‘μˆ˜ κ²°κ³Όλ₯Ό μœ„ν•΄
15+
μ΅œμ†Œκ°’: μŒμˆ˜κ°€ λ‚˜μ€‘μ— μ–‘μˆ˜λ‘œ λ°”λ€” κ°€λŠ₯성을 μœ„ν•΄
16+
17+
μ‹œκ°„ λ³΅μž‘λ„: O(n)
18+
배열을 ν•œ 번만 μˆœνšŒν•˜λ―€λ‘œ O(n)
19+
각 μ›μ†Œμ—μ„œ μƒμˆ˜ μ‹œκ°„μ˜ μ—°μ‚°λ§Œ μˆ˜ν–‰
20+
21+
곡간 λ³΅μž‘λ„: O(1)
22+
μΆ”κ°€ 배열을 μ‚¬μš©ν•˜μ§€ μ•ŠμŒ
23+
λͺ‡ 개의 λ³€μˆ˜λ§Œ μ‚¬μš©ν•˜λ―€λ‘œ μƒμˆ˜ 곡간
24+
'''
25+
26+
class Solution:
27+
def maxProduct(self, nums: List[int]) -> int:
28+
# 빈 λ°°μ—΄ 처리
29+
if not nums:
30+
return 0
31+
32+
# 첫 번째 μ›μ†Œλ‘œ λͺ¨λ“  값듀을 μ΄ˆκΈ°ν™”
33+
max_product = nums[0] # 전체 μ΅œλŒ€κ°’
34+
current_max = nums[0] # ν˜„μž¬ μœ„μΉ˜κΉŒμ§€μ˜ μ΅œλŒ€ κ³±
35+
current_min = nums[0] # ν˜„μž¬ μœ„μΉ˜κΉŒμ§€μ˜ μ΅œμ†Œ κ³±
36+
37+
# 두 번째 μ›μ†ŒλΆ€ν„° 배열을 μˆœνšŒν•˜λ©° ν˜„μž¬ 숫자λ₯Ό μ €μž₯
38+
for i in range(1, len(nums)):
39+
num = nums[i]
40+
41+
# ν˜„μž¬ μˆ«μžκ°€ 음수일 경우λ₯Ό λŒ€λΉ„ν•΄ max와 min을 μž„μ‹œ μ €μž₯
42+
temp_max = current_max
43+
44+
# μƒˆλ‘œμš΄ μ΅œλŒ€κ°’ 계산: μ΅œλŒ€κ°’κ³Ό μ΅œμ†Œκ°’ λͺ¨λ‘ μ•„λž˜μ˜ 3개 μ€‘μ—μ„œ λ‚˜μ˜¬ 수 있음
45+
# num : ν˜„μž¬ μˆ«μžλΆ€ν„° μƒˆλ‘œ μ‹œμž‘
46+
# temp_max * num : ν˜„μž¬μˆ«μž Γ— μ΄μ „μ΅œλŒ€κ°’
47+
# current_min * num : ν˜„μž¬μˆ«μž Γ— μ΄μ „μ΅œμ†Œκ°’(음수*음수=μ–‘μˆ˜ κ°€λŠ₯μ„± 떄문에)
48+
current_max = max(num, temp_max * num, current_min * num)
49+
50+
# μƒˆλ‘œμš΄ μ΅œμ†Œκ°’ 계산: λ‚˜μ€‘μ— μŒμˆ˜μ™€ κ³±ν•΄μ Έμ„œ 큰 μ–‘μˆ˜κ°€ 될 κ°€λŠ₯성을 μœ„ν•΄
51+
# ν˜„μž¬ 숫자, ν˜„μž¬μˆ«μžΓ—μ΄μ „μ΅œλŒ€, ν˜„μž¬μˆ«μžΓ—μ΄μ „μ΅œμ†Œ 쀑 μ΅œμ†Œ
52+
current_min = min(num, temp_max * num, current_min * num)
53+
54+
# μ§€κΈˆκΉŒμ§€μ˜ 전체 μ΅œλŒ€κ°’κ³Ό ν˜„μž¬ μ΅œλŒ€κ°’μ„ λΉ„κ΅ν•˜μ—¬ μ—…λ°μ΄νŠΈ
55+
max_product = max(max_product, current_max)
56+
57+
return max_product
58+
59+

0 commit comments

Comments
Β (0)