File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed
longest-common-subsequence Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(m * n) m : the length of text1, n : the length of text2
2
+ // Space Complexity: O(m * n)
3
+
4
+ var longestCommonSubsequence = function ( text1 , text2 ) {
5
+ // a memoization array to store results
6
+ const memo = Array ( text1 . length )
7
+ . fill ( null )
8
+ . map ( ( ) => Array ( text2 . length ) . fill ( null ) ) ;
9
+
10
+ // helper function that uses recursion and memoization
11
+ function lcsHelper ( i , j ) {
12
+ // if either string is exhausted, return 0
13
+ if ( i === text1 . length || j === text2 . length ) {
14
+ return 0 ;
15
+ }
16
+
17
+ // if characters match, move diagonally and add 1 to the result
18
+ if ( text1 [ i ] === text2 [ j ] ) {
19
+ memo [ i ] [ j ] = 1 + lcsHelper ( i + 1 , j + 1 ) ;
20
+ } else {
21
+ // if characters don't match, take the maximum result from moving right or down
22
+ memo [ i ] [ j ] = Math . max ( lcsHelper ( i + 1 , j ) , lcsHelper ( i , j + 1 ) ) ;
23
+ }
24
+
25
+ return memo [ i ] [ j ] ;
26
+ }
27
+
28
+ // start the recursion from the beginning of both strings
29
+ return lcsHelper ( 0 , 0 ) ;
30
+ } ;
Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(1)
3
+
4
+ var maxSubArray = function ( nums ) {
5
+ let maxSum = nums [ 0 ] ;
6
+ let currentSum = 0 ;
7
+
8
+ // iterate through the array
9
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
10
+ // if currentSum is negative, reset it to 0
11
+ if ( currentSum < 0 ) {
12
+ currentSum = 0 ;
13
+ }
14
+
15
+ // add the current element to currentSum
16
+ currentSum += nums [ i ] ;
17
+
18
+ // update maxSum if currentSum is greater
19
+ if ( currentSum > maxSum ) {
20
+ maxSum = currentSum ;
21
+ }
22
+ }
23
+
24
+ // return the maximum subarray sum
25
+ return maxSum ;
26
+ } ;
You can’t perform that action at this time.
0 commit comments