File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ // ๋ฐฐ์ด์์ ์ธ์ ํ ํญ์ ์ ๊ทผํ ์ ์์ ๋, ์ธ์ ํ์ง ์์ ํญ์ ๋ํด ๊ฐ์ฅ ํฐ ๊ฐ์ ๊ตฌํ๋ ๋ฌธ์
3
+ // 1. DP๋ฅผ ์ฌ์ฉํด ๊ฐ ์ง๋ง๋ค ์ ํํ๊ฑฐ๋ ๊ฑด๋๋ฐ๋ ๊ฒฝ์ฐ๋ฅผ ๋์ ๊ณ์ฐ
4
+ // 2. ํ์ฌ ์ง์ ํธ ๋, ์ด์ ์ง์ ํธ์ง ์์ ๊ฒฝ์ฐ๋ง ๋ํ ์ ์๊ฒ๋ ๊ณ์ฐ
5
+ fun rob (nums : IntArray ): Int {
6
+ if (nums.isEmpty()) return 0
7
+ var prev1 = 0 // ๋ฐ๋ก ์ด์ ์ง๊น์ง์ ์ต๋ ์ด์ต
8
+ var prev2 = 0 // ์ด์ ์ด์ ์ง๊น์ง์ ์ต๋ ์ด์ต
9
+
10
+ for (num in nums) {
11
+ var temp = prev1
12
+ prev1 = maxOf(prev2 + num, prev1)
13
+ prev2 = temp
14
+ }
15
+
16
+ return prev1
17
+ }
18
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ // ๋ฐฐ์ด์์ ์ฐ์๋ ์ซ์์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์
3
+ // 1. ์ค๋ณต์ ์ ๊ฑฐํ๊ณ ์นด์ดํธ
4
+ // 2. ์ ๋ ฌํ์ง ์๊ณ ๊ณ์ฐ๋ ๊ฐ๋ฅ
5
+ fun longestConsecutive (nums : IntArray ): Int {
6
+ if (nums.isEmpty()) return 0
7
+
8
+ val numSet = nums.toHashSet()
9
+ var maxLen = 0
10
+
11
+ for (num in nums){
12
+ if ((num - 1 ) !in numSet){
13
+ var currNum = num
14
+ var currLen = 1
15
+
16
+ while ((currNum + 1 ) in numSet){
17
+ currNum++
18
+ currLen++
19
+ }
20
+ if (currLen > maxLen) maxLen = currLen
21
+ }
22
+ }
23
+ return maxLen
24
+ }
25
+ }
You canโt perform that action at this time.
0 commit comments