File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def rob (self , nums : List [int ]) -> int :
3+
4+ # [2,7,9,10,5,4]
5+ # No Consecutive robbing --> able to skip as many times as wanted
6+
7+ # which one to add? --> dp
8+
9+ # dp[i], dp[i-1] + nums[i+1]
10+ if len (nums ) == 1 :
11+ return nums [0 ]
12+
13+
14+ dp = [0 ]* len (nums )
15+ dp [0 ] = nums [0 ]
16+ dp [1 ] = max (dp [0 ], nums [1 ])
17+
18+ for i in range (2 , len (nums )):
19+ dp [i ] = max (dp [i - 1 ], dp [i - 2 ] + nums [i ])
20+
21+ return dp [- 1 ]
Original file line number Diff line number Diff line change 1+ from collections import defaultdict
2+ class Solution :
3+ def longestConsecutive (self , nums : List [int ]) -> int :
4+
5+ if not nums :
6+ return 0
7+
8+ dict_consecutive = defaultdict (int )
9+ group_num = 0 # consecutive group number
10+
11+ dict_consecutive [group_num ] += 1 # w.r.t the first num of nums
12+
13+ # sort in the ascending order eliminating duplicates
14+ nums = sorted (set (nums ))
15+
16+ # 2. build dict_consecutive
17+ for i in range (1 , len (nums )):
18+ if nums [i ] - nums [i - 1 ] == 1 :
19+ dict_consecutive [group_num ] += 1
20+ else :
21+ group_num += 1
22+ dict_consecutive [group_num ] += 1
23+
24+ # 3. Get the longest group
25+ longest_consecutive = max (list (dict_consecutive .values ()))
26+
27+ return longest_consecutive
28+
You can’t perform that action at this time.
0 commit comments