Skip to content

Commit 2f39ee6

Browse files
authored
Create minimum-operations-to-make-a-subsequence.cpp
1 parent ee1fb0e commit 2f39ee6

File tree

1 file changed

+122
-0
lines changed

1 file changed

+122
-0
lines changed
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int minOperations(vector<int>& target, vector<int>& arr) {
7+
unordered_map<int, int> lookup;
8+
for (int i = 0; i < size(target); ++i) {
9+
lookup[target[i]] = i;
10+
}
11+
vector<int> lis;
12+
for (const auto& x : arr) {
13+
if (!lookup.count(x)) {
14+
continue;
15+
}
16+
auto it = lower_bound(begin(lis), end(lis), lookup[x]);
17+
if (it == end(lis)) {
18+
lis.emplace_back(lookup[x]);
19+
} else {
20+
*it = lookup[x];
21+
}
22+
}
23+
return size(target) - size(lis);
24+
}
25+
};
26+
27+
// Time: O(nlogn)
28+
// Space: O(n)
29+
// segment tree solution
30+
class Solution2 {
31+
public:
32+
int minOperations(vector<int>& target, vector<int>& arr) {
33+
unordered_map<int, int> lookup;
34+
for (int i = 0; i < size(target); ++i) {
35+
lookup[target[i]] = i;
36+
}
37+
SegmentTree st(size(lookup));
38+
for (const auto& x : arr) {
39+
if (!lookup.count(x)) {
40+
continue;
41+
}
42+
st.update(lookup[x], lookup[x], (lookup[x] >= 1) ? st.query(0, lookup[x] - 1) + 1 : 1);
43+
}
44+
return size(target) - ((size(lookup) >= 1) ? st.query(0, size(lookup) - 1) : 0);
45+
}
46+
47+
private:
48+
class SegmentTree {
49+
public:
50+
SegmentTree(int N)
51+
: N_(N),
52+
tree_(2 * N),
53+
lazy_(N)
54+
{
55+
H_ = 1;
56+
while ((1 << H_) < N) {
57+
++H_;
58+
}
59+
}
60+
61+
void update(int L, int R, int h) {
62+
L += N_; R += N_;
63+
int L0 = L, R0 = R;
64+
while (L <= R) {
65+
if ((L & 1) == 1) {
66+
apply(L++, h);
67+
}
68+
if ((R & 1) == 0) {
69+
apply(R--, h);
70+
}
71+
L >>= 1; R >>= 1;
72+
}
73+
pull(L0); pull(R0);
74+
}
75+
76+
int query(int L, int R) {
77+
L += N_; R += N_;
78+
auto result = 0;
79+
push(L); push(R);
80+
while (L <= R) {
81+
if ((L & 1) == 1) {
82+
result = max(result, tree_[L++]);
83+
}
84+
if ((R & 1) == 0) {
85+
result = max(result, tree_[R--]);
86+
}
87+
L >>= 1; R >>= 1;
88+
}
89+
return result;
90+
}
91+
92+
private:
93+
int N_, H_;
94+
vector<int> tree_, lazy_;
95+
96+
void apply(int x, int val) {
97+
tree_[x] = max(tree_[x], val);
98+
if (x < N_) {
99+
lazy_[x] = max(lazy_[x], val);
100+
}
101+
}
102+
103+
void pull(int x) {
104+
while (x > 1) {
105+
x >>= 1;
106+
tree_[x] = max(tree_[x * 2], tree_[x * 2 + 1]);
107+
tree_[x] = max(tree_[x], lazy_[x]);
108+
}
109+
}
110+
111+
void push(int x) {
112+
for (int h = H_; h > 0; --h) {
113+
int y = x >> h;
114+
if (lazy_[y] > 0) {
115+
apply(y * 2, lazy_[y]);
116+
apply(y * 2 + 1, lazy_[y]);
117+
lazy_[y] = 0;
118+
}
119+
}
120+
}
121+
};
122+
};

0 commit comments

Comments
 (0)