Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <string>
- #include <algorithm>
- using namespace std;
- string maxSubsequence(string num, int k) {
- int n = num.size();
- // We need to remove (n - k) digits.
- int removals = n - k;
- string result;
- for (char digit : num) {
- // While we can remove more digits and the last digit in the result is less than the current digit,
- // remove the last digit.
- while (!result.empty() && removals > 0 && result.back() < digit) {
- result.pop_back();
- removals--;
- }
- result.push_back(digit);
- }
- // If we still have removals left, remove them from the end.
- while (removals > 0) {
- result.pop_back();
- removals--;
- }
- // The result might be longer than k if we never removed enough digits.
- return result.substr(0, k);
- }
- int main() {
- // Example: using digits from the array [4, 9, 0, 2] represented as string "4902"
- string num = "4902";
- int k = 2;
- cout << "Maximum subsequence of length " << k << ": " << maxSubsequence(num, k) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement