File tree Expand file tree Collapse file tree 2 files changed +51
-13
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 2 files changed +51
-13
lines changed Original file line number Diff line number Diff line change 1+ # idea: DP Top-down / Bottom-up
2+ # DP was comp up on my head, but it is not easy for me to utilse recursive function.
3+
4+
5+ class Solution :
6+ def rob (self , nums : List [int ]) -> int :
7+ length = len (nums )
8+ if length == 0 :
9+ return 0
10+ if length == 1 :
11+ return nums [0 ]
12+
13+ lst = [0 ]* length
14+ lst [0 ] = nums [0 ]
15+ lst [1 ] = max (nums [0 ], nums [1 ])
16+
17+ for i in range (2 , length ):
18+ lst [i ] = max (lst [i - 1 ], lst [i - 2 ] + nums [i ])
19+
20+ return lst [- 1 ]
Original file line number Diff line number Diff line change 11# idea: -
2+
23class Solution :
34 def longestConsecutive (self , nums : List [int ]) -> int :
4- sorted_nums = sorted (list (set (nums )))
5- # sorted_nums = sorted(nums) # duplicate
6- max_len = 1
7- tmp = 1
8-
9- for i in range (1 , len (sorted_nums )):
10- if sorted_nums [i ] == sorted_nums [i - 1 ] + 1 :
11- tmp += 1
12- else :
13- max_len = max (max_len , tmp )
14- tmp = 1
15- ans = max (max_len , tmp )
16- return ans
5+ ans = 0
6+ return ans
7+
8+
9+
10+ '''
11+ Trial and error
12+
13+ The code below was passed on Leecode since their Constraints was 0 <= nums.length <= 10^5.
14+ But I realised that I missed another constraint they mentioned, which is "You must write an algorithm that runs in O(n) time."
15+ '''
16+ # class Solution:
17+ # def longestConsecutive(self, nums: List[int]) -> int:
18+ # if len(nums)==0:
19+ # return 0
20+ # sorted_nums = sorted(list(set(nums)))
21+ # # sorted_nums = sorted(nums) # duplicate
22+ # max_len = 1
23+ # tmp = 1
24+
25+ # for i in range(1, len(sorted_nums)):
26+ # if sorted_nums[i] == sorted_nums[i - 1] + 1:
27+ # tmp += 1
28+ # else:
29+ # max_len = max(max_len, tmp)
30+ # tmp = 1
31+ # ans = max(max_len, tmp)
32+ # return ans
33+
34+
1735
You can’t perform that action at this time.
0 commit comments