We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent abc6485 commit ade5a51Copy full SHA for ade5a51
โhouse-robber/kut7728.swift
@@ -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