File tree 1 file changed +41
-0
lines changed
scripts/algorithms/M/Minimum Operations to Make a Subsequence
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ const minOperations = function ( targets , arr ) {
2
+ const map = { } ;
3
+ const n = targets . length ;
4
+ const m = arr . length ;
5
+ targets . forEach ( ( target , i ) => ( map [ target ] = i ) ) ;
6
+
7
+ //map elements in arr to index found in targets array
8
+ const arrIs = arr . map ( el => {
9
+ if ( el in map ) {
10
+ return map [ el ] ;
11
+ } else {
12
+ return - 1 ;
13
+ }
14
+ } ) ;
15
+
16
+ //create a LIS table dp whose length is the longest increasing subsequence
17
+ const dp = [ ] ;
18
+
19
+ for ( let i = 0 ; i < m ; i ++ ) {
20
+ const curr = arrIs [ i ] ;
21
+ if ( curr === - 1 ) continue ;
22
+ if ( ! dp . length || curr > dp [ dp . length - 1 ] ) {
23
+ dp . push ( curr ) ;
24
+ } else if ( curr < dp [ 0 ] ) {
25
+ dp [ 0 ] = curr ;
26
+ } else {
27
+ let l = 0 ;
28
+ let r = dp . length ;
29
+ while ( l < r ) {
30
+ const mid = Math . floor ( ( l + r ) / 2 ) ;
31
+ if ( arrIs [ i ] <= dp [ mid ] ) {
32
+ r = mid ;
33
+ } else {
34
+ l = mid + 1 ;
35
+ }
36
+ }
37
+ dp [ r ] = curr ;
38
+ }
39
+ }
40
+ return n - dp . length ;
41
+ } ;
You can’t perform that action at this time.
0 commit comments