Skip to content

Commit ceaff05

Browse files
author
แ„‹แ…ตแ„‹แ…งแ†ซแ„‰แ…ฎ
committed
House Robber
1 parent df80b67 commit ceaff05

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package leetcode_study
2+
3+
/**
4+
* DP๋ฅผ ์‚ฌ์šฉํ•œ ๋ฌธ์ œ ํ’€์ด.
5+
* DP๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•˜์—ฌ ์ตœ๋Œ€ ๊ฐ’์„ ๊ตฌํ•˜๋ ค๋ฉด 100!์— ํ•ด๋‹นํ•˜๋Š” ์—ฐ์‚ฐ์ด ํ•„์š”ํ•˜๋ฉฐ, ์ด๋Š” ์‹œ๊ฐ„ ์ดˆ๊ณผ๋ฅผ ์ดˆ๋ž˜ํ•ฉ๋‹ˆ๋‹ค.
6+
* ์‹œ๊ฐ„ ๋ณต์žก๋„ : O(n)
7+
* -> ์ฃผ์–ด์ง„ ์ˆซ์ž ๋ฐฐ์—ด ๋งŒํผ ๋ฐ˜๋ณต ์ง„ํ–‰
8+
* ๊ณต๊ฐ„ ๋ณต์žก๋„ : O(n)
9+
* -> ์ˆซ์ž ๋ฐฐ์—ด๋งŒํผ์˜ ๊ฐ€์ค‘์น˜๋ฅผ ๋‹ด์„ ๋ฐฐ์—ด ํ•„์š”
10+
*/
11+
fun rob(nums: IntArray): Int {
12+
val dp = IntArray(nums.size)
13+
14+
if (nums.size == 1) {
15+
return nums[0]
16+
}
17+
18+
if (nums.size == 2) {
19+
return max(nums[0], nums[1])
20+
}
21+
22+
dp[0] = nums[0]
23+
dp[1] = nums[1]
24+
dp[2] = nums[2] + dp[0]
25+
26+
for (i in 3 until nums.size) {
27+
dp[i] = max(dp[i-3], dp[i-2]) + nums[i]
28+
}
29+
return dp.max()
30+
}

0 commit comments

Comments
ย (0)