[LeetCode] Minimum Operations to Make a Subsequence

1713. Minimum Operations to Make a Subsequence

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 the minimum number of operations needed to make target a subsequence 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
unordered_map<int, int> m;
public:
int minOperations(vector<int>& target, vector<int>& arr) {
for(int i = 0; i < target.size(); i++) {
m[target[i]] = i;
}
vector<int> st{-987654321};
for(auto& n : arr) {
if(!m.count(n)) continue;
if(st.back() < m[n]) {
st.push_back(m[n]);
} else {
auto it = lower_bound(st.begin(), st.end(), m[n]);
*it = m[n];
}
}

return target.size() - st.size() + 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/31/PS/LeetCode/minimum-operations-to-make-a-subsequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.