Skip to content

Commit ade5a51

Browse files
committed
house-robber solved
1 parent abc6485 commit ade5a51

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

house-robber/kut7728.swift

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
func rob(_ nums: [Int]) -> Int {
3+
let n = nums.count
4+
if n == 0 { return 0 }
5+
if n == 1 { return nums[0] }
6+
if n == 2 { return max(nums[0], nums[1]) }
7+
8+
//dp[i]는 i번까지 고려했을 때 가능한 최대 금액
9+
var dp = [Int](repeating: 0, count: n)
10+
dp[0] = nums[0]
11+
dp[1] = max(nums[0], nums[1]) //첫째 or 둘째 집 중 더 비싼 집 털기
12+
13+
//각 dp의 자리에는 바로 전 값을 그대로 가져오거나(i를 안털기), 전전집까지 턴거+i턴 값 중에서 비싼쪽 저장
14+
for i in 2..<n {
15+
dp[i] = max(dp[i-1], dp[i-2] + nums[i])
16+
}
17+
18+
//마지막 집까지 고려한 최대 이익 반환하기
19+
return dp[n - 1]
20+
}
21+
}

0 commit comments

Comments
 (0)