
์๊ฐ ๋ฐฉ์
Brute force๋ก ์ถฉ๋ถํ ํ ์ ์๋ ๋ฌธ์ ๋ค
ํ์ง๋ง ์ฝ๋ฉ ํ ์คํธ ํน์ฑ์ ๊ทธ๋ฆฌ๊ณ ๋ฌธ์ ์ ๋์ด๋๋ฅผ ๋ณด์ํ๋ brute force๋ก ํ๋ฉด ๋ฐํ์ ์๋ฌ๊ฐ ๋ฐ๊ฒ ๋ถ๋ช ํ๋ค
๊ทธ๋ ๋ค๋ฉด Greedy ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉํด ๋ณธ๋ค
์ผ๋จ ๋ง์ง๋ง์ผ๋ก ์ค ํ ์คํธ ์ผ์ด์ค๊ฐ ์ ์ผ ๋ณด๊ธฐ ํธํ์ง๋ง ์ต๋๊ฐ์ ๊ฒฐ๊ตญ ๋ชจ๋ ์๋ฅผ ๋ํ ๊ฑฐ๋ผ ๋ณ ์๋ฏธ๊ฐ ์์ด ๋ณด์ฌ [5,4,-10,7,8,10]๋ฅผ ํ ์คํธ ์ผ์ด์ค๋ก ๋ง๋ค์ด ๋ดค๋ค.
์กฐ๊ธ๋ง ํ์ด๋ณด๋ฉด [7,8,10]์ด maxSubArray๋ผ๋ ๊ฒ์ ์ฐ๋ฆฌ๋ ์ ์ ์๋ค.
๋์ถฉ ๊ธ๋ก ๋จผ์ ์ฝ๋๋ฅผ ์์ฑํ๋ค
maxSubVal = 0
current = 0
loop through every numbers in nums array:
if current is less than 0, then reset current as 0. greedy
add numbers from nums array to current
compare with maxSubVal with current and find the maximum value from those two
return the maximum value that we found
์ผ์ด๋ ๋ฌธ์
์ผ๋จ current๋ผ๋ ๋ณ์๋ฅผ 0์ผ๋ก ์ค์ ํด ์ฃผ๊ณ , maxSub๋ผ๋ ๋ณ์๋ 0์ผ๋ก ์ค์ ํด ์คฌ๋ค
๊ทผ๋ฐ nums๊ฐ ๋ค ์์์ผ ๋ ํ ์คํธ ์ผ์ด์ค๋ฅผ ํต๊ณผํ์ง ๋ชปํ๋ค.
์๋ฅผ ๋ค๋ฉด [-2]๊ฐ nums๋ผ๋ฉด, loop์ ๋๋ฆด ๋ current๋ -2๊ฐ ๋ ๊ฒ์ด๊ณ , maxSubVal์ 0์ด๋๊น, ๊ฒฐ๊ณผ๋ก 0์ด ๋์ค๊ฒ ๋๋ค
๊ทผ๋ฐ 0์ด๋ผ๋ ์ซ์๋ ์ ์ด์ nums ์์ ์กด์ฌํ์ง ์๊ธฐ ๋๋ฌธ์ ์๋ฌ๊ฐ ๋๋ ๊ฒ์ด๋ค
๊ทธ๋์ maxSubVal๋ฅผ nums[0]์ผ๋ก ์ง์ ํด ์ค์ ํด๊ฒฐ์ ํด๋ดค๋ค
๐ป ๋ง์ง๋ง์ผ๋ก ์์ ํ ์ ์ถํ ์ฝ๋
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maxSub = nums[0]
current = 0
for num in nums:
if current < 0:
current = 0
current += num
maxSub = max(maxSub, current)
return maxSub
๊ทธ๋ฆผ์ผ๋ก ์ค๋ช


'์ฝ๋ฉ ํ ์คํธ > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| 226. Invert Binary Tree (Easy) [Java] (0) | 2024.02.09 |
|---|---|
| 55. Jump Game (Medium) [Python] (0) | 2024.02.04 |
| 746. Min Cost Climbing Stairs (Easy) [Python] (0) | 2024.02.04 |
| 70. Climbing Stairs (Easy) [Python] (2) | 2024.02.03 |
| 49. Group Anagrams (Medium) [Python] (0) | 2024.02.03 |