Skip to content

Commit 0953f26

Browse files
committed
Feat: Add solution of house-robber
1 parent ed398ff commit 0953f26

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// 풀이
2+
// dpλ₯Ό μ‚¬μš©ν•˜μ—¬ ν˜„μž¬ ν„Έ 수 μžˆλŠ” μ΅œλŒ€ν•œμ˜ λˆμ„ 계산
3+
// curr이 prevκ°€ 되고, prevμ˜€λ˜ 값이 μƒˆλ‘œμš΄ 값을 λ”ν•œ 것과 curr μ΄μ—ˆλ˜ κ°’μ˜ μ΅œλŒ€κ°’μ„ λΉ„κ΅ν•œ 것이 μƒˆλ‘œμš΄ curr이 λœλ‹€.
4+
// λ§ˆμ§€λ§‰μ—” prev와 curr의 μ΅œλŒ€κ°’μ„ 비ꡐ
5+
// μ΄λ ‡κ²Œ ν•˜λ©΄ ν„Έ 수 μžˆλŠ” μ§‘μ˜ μ΅œλŒ€κ°’μ„ 계속 κ°€μ§€κ³  μžˆμ„ 수 있게 됨.
6+
7+
// TC
8+
// O(n)
9+
10+
// SC
11+
// λŠ˜μ–΄λ‚˜μ§€ μ•ŠλŠ” int κ°’λ§Œ μ‚¬μš©ν–ˆμœΌλ―€λ‘œ O(1)
12+
13+
func rob(nums []int) int {
14+
length := len(nums)
15+
16+
if length == 1 {
17+
return nums[0]
18+
}
19+
20+
prev := 0
21+
curr := nums[0]
22+
23+
for i := 1; i < length; i++ {
24+
prev, curr = curr, max(nums[i]+prev, curr)
25+
}
26+
27+
return max(prev, curr)
28+
}
29+
30+
func max(a, b int) int {
31+
if a > b {
32+
return a
33+
} else {
34+
return b
35+
}
36+
}

0 commit comments

Comments
Β (0)