File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ ๏ปฟ# --- ํด์ ---
2+ #๋งค๊ฐ๋ณ์ nums ๋ฅผ ์ํํ๋ฉด์ nums[i] ์ผ๋์ ์ต๋ ๋์ ๊ฐ์ ์
๋ฐ์ดํธ ํ๋ค
3+ #prev1์ ํ์ฌ๊น์ง์ ์ต๊ณ ๋์ ๊ธ์ก, prev2๋ ์ด์ ์ง๊น์ง์ ์ต๊ณ ๋์ ๊ธ์ก์ด๋ค.
4+ #ํ์ฌ ์ง nums[i] ๋ฅผ ๋๋์ง ํ๋ ค๋ฉด, ์ด์ ์ง๊น์ง์ ์ต๊ณ ๊ธ์ก(prev2) + ํ์ฌ ์ง(nums[i])์ด๋ค.
5+ #ํ์ฌ ์ง nums[i]๋ฅผ ๋๋์ง์ ์ ์ธํ๋ ค๋ฉด ํ์ฌ๊น์ง์ ์ต๊ณ ๊ธ์(prev1) ์ด๋ค.
6+ #loop ๋น ์ ๋์ ์ต๋๊ฐ์ ์ ํํ์ฌ current๋ณ์์ updateํด์ค๋ค.
7+
8+ # --- Big O
9+ #N: ๋งค๊ฐ๋ณ์ nums์ ๊ธธ์ด๊ฐ N์ด๋ค.
10+
11+ # Time Complexity: O(N)
12+ #- for loop ๋ nums[0] ๋ถํฐ nums[len(nums)]๋งํผ ์ํ: O(N)
13+
14+ # Space Complexity: O(1)
15+ #-current,prev1,prev2 ๋ nums์ ๋ฌด๊ดํ ์์ ๋ฉ๋ก๋ฆฌ ํ ๋น: O(1)
16+
17+
18+ class Solution (object ):
19+ def rob (self , nums ):
20+ """
21+ :type nums: List[int]
22+ :rtype: int
23+ """
24+ #prev1: ํ์ฌ ์ง๊น์ง์ ์ต๊ณ ๊ธ์ก
25+ #prev2: ์ด์ด์ ์ง๊น์ง์ ์ต๊ณ ๊ธ์ก
26+ prev1 ,prev2 = 0 ,0
27+
28+ for num in nums :
29+ #current๋ prev1๊ณผ prev2+num ์ค ํฐ ๊ฐ์ update
30+ current = max (prev1 ,prev2 + num )
31+ prev2 = prev1 #current์
๋ฐ์ดํธ ์ดํ prev1(ํ์ฌ ์ต๊ณ ๊ธ์ก) ์ด prev2(์ด์ด์ง ์ง๊น์ง ์ต๊ณ ๊ธ์ก)๊ฐ๋๋ค
32+ prev1 = current #prev1์ ํ num๊น์ง ๊ณ ๋ ค๋ current์ ๊ฐ์ด๋ค. (ํ์ฌ ์ต๊ณ ๊ธ์ก์ก)
33+ return prev1
34+ nums = [2 ,7 ,9 ,3 ,1 ]
35+ solution = Solution ()
36+ solution .rob (nums )
37+
You canโt perform that action at this time.
0 commit comments