File tree Expand file tree Collapse file tree 5 files changed +90
-0
lines changed
longest-common-subsequence
longest-increasing-subsequence Expand file tree Collapse file tree 5 files changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def canJump (self , nums : List [int ]) -> bool :
3
+ target = len (nums ) - 1
4
+
5
+ for i in range (target , - 1 , - 1 ):
6
+ if i + nums [i ] >= target :
7
+ target = i
8
+
9
+ return True if target == 0 else False
10
+
11
+ # maxReach = 0
12
+ # for i, jump in enumerate(nums):
13
+ # if i > maxReach:
14
+ # return False
15
+ # maxReach = max(maxReach, i + jump)
16
+ # return True
17
+
18
+ ## Both TC: O(n), SC: O(1)
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def longestCommonSubsequence (self , text1 : str , text2 : str ) -> int :
3
+ dp = [0 ] * (len (text2 ) + 1 )
4
+
5
+ for i in range (len (text1 )):
6
+ prev_row = dp [:]
7
+ for j in range (len (text2 )):
8
+ if text1 [i ] == text2 [j ]:
9
+ dp [j + 1 ] = prev_row [j ] + 1
10
+ else :
11
+ dp [j + 1 ] = max (dp [j ], prev_row [j + 1 ])
12
+
13
+ return dp [- 1 ]
14
+
15
+ ## TC: O(mn), SC: O(n)
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def lengthOfLIS (self , nums : List [int ]) -> int :
3
+ arr = [nums .pop (0 )]
4
+
5
+ for n in nums :
6
+ if n > arr [- 1 ]:
7
+ arr .append (n )
8
+ else :
9
+ arr [bisect_left (arr , n )] = n
10
+
11
+ return len (arr )
12
+
13
+ ## TC: O(nlogn) SC: O(n)
14
+
15
+ # if not nums:
16
+ # return 0
17
+
18
+ # n = len(nums)
19
+ # LIS = [1] * n
20
+
21
+ # for i in range(1, n):
22
+ # for j in range(i):
23
+ # if nums[i] > nums[j]:
24
+ # LIS[i] = max(LIS[i], 1 + LIS[j])
25
+
26
+ # return max(LIS)
27
+
28
+ ## DP solution: TC: O(n^2) O(n)
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def maxSubArray (self , nums : List [int ]) -> int :
3
+
4
+ maxSub = nums [0 ]
5
+ curSum = 0
6
+
7
+ for n in nums :
8
+ if curSum < 0 :
9
+ curSum = 0
10
+
11
+ curSum += n
12
+ maxSub = max (curSum , maxSub )
13
+
14
+ return maxSub
15
+
16
+ ## TC: O(n), SC: O(1)
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def uniquePaths (self , m : int , n : int ) -> int :
3
+ dp = [1 ] * n
4
+
5
+ for _ in range (1 , m ):
6
+ for i in range (1 , n ):
7
+ dp [i ] += dp [i - 1 ]
8
+
9
+ return dp [- 1 ]
10
+ ## TC: O(mn), SC: O(n)
11
+
12
+ ## return math.comb(m + n - 2, m - 1)
13
+ ## TC: O(1) whatever constant, SC: O(1)
You can’t perform that action at this time.
0 commit comments