-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmaximum_subarray.py
More file actions
23 lines (18 loc) ยท 1.18 KB
/
maximum_subarray.py
File metadata and controls
23 lines (18 loc) ยท 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 53. Maximum Subarray
# https://leetcode.com/problems/maximum-subarray/
from typing import List
class Solution:
# ์ฃผ์ด์ง integer ๋ฆฌ์คํธ์์ ๊ฐ์ฅ ํฐ ๋ถ๋ถ ํฉ(sum)์ ๊ตฌํ๋ ๋ฌธ์ ๋ค.
# ์ฌ๊ธฐ์ ๊ฐ์ฅ maximum sum ์ ๋ฆฌ์คํธ์์ ์ฐ์์ ์ธ ๋ถ๋ถ ๋ฆฌ์คํธ์ ํฉ์ด ๋์ด์ผ ํ๋ค.
def maxSubArray(self, nums: List[int]) -> int:
temp, result = nums[0], nums[0]
# ๊ฐ ๋๊ฐ๋ฅผ ์ฌ์ฉํด์ ํ ์ ์๋ค.
# ์ฒซ๋ฒ์งธ ๊ฐ temp ๋ ํ์ฌ ๊ฐ๊ณผ ํ์ฌ ๊ฐ์ ํฌํจํ sum ์ค ํฐ ๊ฐ์ ๊ฐ๊ณ ๊ฐ๊ณ
# ๋๋ฒ์งธ ๊ฐ result ๋ ๊ทธ๋ฌํ temp ์ค์ ๊ฐ์ฅ ํฐ ๊ฐ์ ๊ฐ์ง๊ณ ๊ฐ๋ค.
# ๊ฐ 2๊ฐ๋ฅผ ์ฌ์ฉํ๋ ์ด์ ๋, ํนํ temp ๋ฅผ ์ฌ์ฉํ๋ ์ด์ ๋ ๊ตฌํด์ผ ํ๋ ํฉ์ ๋ถ๋ถ ๋ฆฌ์คํธ์ ํฉ์ด๋ฉด์
# ํด๋น ๋ฆฌ์คํธ์ ์์ ๊ฐ์ด ๋ค์ด๊ฐ ์ ์๋ค. ๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ์์ ๊ฐ์ ํฌํจํ ๋ถ๋ถ ๋ฆฌ์คํธ์ ํฉ์ด ์ปค์ง๋ ๊ตฌ๊ฐ์ด ์๊ธธ ์ ์์ผ๋ฏ๋ก
# ํ์ฌ ๊ฐ์ ํฌํจํ maximum ๊ฐ์ ํ์ธํด์ผ ํ๋ ๊ฒ์ด๋ค.
for i in range(1, len(nums)):
temp = max(temp + nums[i], nums[i])
result = max(result, temp)
return result