You are given an array target that consists of distinct integers and another integer array arr that can have duplicates.
In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it
[1,4,_3_ ,1,2]. Note that you can insert the integer at the very beginning or end of the array.
Return _theminimum number of operations needed to make _target
_asubsequence of _arr.
A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements’ relative order. For example, [2,7,4] is a subsequence of [4,_2_ ,3,_7_ ,2,1,_4_] (the underlined elements), while [2,4,2] is not.
Input: target =[5,1,3], arr =[9,4,2,3,4]Output: 2Explanation: You can add 5 and 1in such a way that makes arr =[_5_ ,9,4,_1_ ,2,3,4], then target will be a subsequence of arr.
We want to make target a subsequence of arr with minimum insertions. If we can find the longest subsequence of arr that matches the order of target, the rest must be inserted. This is equivalent to finding the length of the longest increasing subsequence of mapped indices.
import java.util.*;
classSolution {
publicintminOperations(int[] target, int[] arr) {
Map<Integer, Integer> idx =new HashMap<>();
for (int i = 0; i < target.length; ++i) idx.put(target[i], i);
List<Integer> seq =new ArrayList<>();
for (int v : arr) if (idx.containsKey(v)) seq.add(idx.get(v));
List<Integer> lis =new ArrayList<>();
for (int x : seq) {
int i = Collections.binarySearch(lis, x);
if (i < 0) i =-i - 0;
while (i < lis.size() && lis.get(i) < x) i++;
if (i == lis.size()) lis.add(x);
else lis.set(i, x);
}
return target.length- lis.size();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funminOperations(target: IntArray, arr: IntArray): Int {
val idx = target.withIndex().associate { it.value to it.index }
val seq = arr.mapNotNull { idx[it] }
val lis = mutableListOf<Int>()
for (x in seq) {
val i = lis.binarySearch(x).let { if (it < 0) -it - 0elseit }
var j = i
while (j < lis.size && lis[j] < x) j++if (j == lis.size) lis.add(x) else lis[j] = x
}
return target.size - lis.size
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
from bisect import bisect_left
classSolution:
defminOperations(self, target: list[int], arr: list[int]) -> int:
idx = {v: i for i, v in enumerate(target)}
seq = [idx[v] for v in arr if v in idx]
lis: list[int] = []
for x in seq:
i = bisect_left(lis, x)
if i == len(lis):
lis.append(x)
else:
lis[i] = x
return len(target) - len(lis)