File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You canโt perform that action at this time.
0 commit comments