[LeetCode] Maximum Number of Removable Characters

1898. Maximum Number of Removable Characters

You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed).

You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence.

Return the maximum k you can choose such that p is still a subsequence of s after the removals.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int maximumRemovals(string s, string p, vector<int>& removable) {
int l = 0, r = removable.size();
vector<int> rm(s.size(), INT_MAX);
for (int i = 0; i < removable.size(); ++i) rm[removable[i]] = i;
while (l < r) {
int m = (l + r + 1) / 2, j = 0;
for (int i = 0; i < s.size() && j < p.size(); ++i) {
if (rm[i] >= m && s[i] == p[j])
++j;
}
if (j == p.size()) l = m;
else r = m - 1;
}
return l;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/01/PS/LeetCode/maximum-number-of-removable-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.