Skip to content

Commit 2423497

Browse files
committed
maximum-product-subarray solution & complexity
1 parent b55cdae commit 2423497

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"""
2+
/풀이 봐도 잘 이해 못해서 추가 코멘트/
3+
nums[i]가 그 전까지 subarray의 합 total보다 작은 음수인 케이스는 어떻게 되는거지 고민했는데
4+
ex) total : -1, nums[i] = -2
5+
어차피 -1인 시점에 maxTotal이 업데이트 됐으므로 total은 nums[i]부터 더하기 시작한다는 의미로 -2로 설정한다는 것을 깨달음
6+
따라서 이전까지 subarray의 합만 음수 양수 체크
7+
8+
TC : for문 한번
9+
=> O(N)
10+
SC : 추가적인 배열 등 메모리 쓰지 않으므로
11+
=> O(1)
12+
"""
13+
class Solution:
14+
def maxSubArray(self, nums: List[int]) -> int:
15+
total = nums[0]
16+
maxTotal = nums[0]
17+
for i in range(1, len(nums)) :
18+
if (total < 0) :
19+
total = nums[i]
20+
else :
21+
total += nums[i]
22+
maxTotal = max(total, maxTotal)
23+
return (maxTotal)

0 commit comments

Comments
 (0)