Advertisement
aqibm

Untitled

Apr 5th, 2025
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. string maxSubsequence(string num, int k) {
  8. int n = num.size();
  9. // We need to remove (n - k) digits.
  10. int removals = n - k;
  11. string result;
  12.  
  13. for (char digit : num) {
  14. // While we can remove more digits and the last digit in the result is less than the current digit,
  15. // remove the last digit.
  16. while (!result.empty() && removals > 0 && result.back() < digit) {
  17. result.pop_back();
  18. removals--;
  19. }
  20. result.push_back(digit);
  21. }
  22.  
  23. // If we still have removals left, remove them from the end.
  24. while (removals > 0) {
  25. result.pop_back();
  26. removals--;
  27. }
  28.  
  29. // The result might be longer than k if we never removed enough digits.
  30. return result.substr(0, k);
  31. }
  32.  
  33. int main() {
  34. // Example: using digits from the array [4, 9, 0, 2] represented as string "4902"
  35. string num = "4902";
  36. int k = 2;
  37. cout << "Maximum subsequence of length " << k << ": " << maxSubsequence(num, k) << endl;
  38. return 0;
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement