SHARE
    TWEET
    aqibm

    Untitled

    Apr 5th, 2025
    49
    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. string maxSubsequence(string num, int k) {
    7. int n = num.size();
    8. // We need to remove (n - k) digits.
    9. int removals = n - k;
    10. string result;
    11. for (char digit : num) {
    12. // While we can remove more digits and the last digit in the result is less than the current digit,
    13. // remove the last digit.
    14. while (!result.empty() && removals > 0 && result.back() < digit) {
    15. result.pop_back();
    16. removals--;
    17. }
    18. result.push_back(digit);
    19. }
    20. // If we still have removals left, remove them from the end.
    21. while (removals > 0) {
    22. result.pop_back();
    23. removals--;
    24. }
    25. // The result might be longer than k if we never removed enough digits.
    26. return result.substr(0, k);
    27. }
    28. int main() {
    29. // Example: using digits from the array [4, 9, 0, 2] represented as string "4902"
    30. string num = "4902";
    31. int k = 2;
    32. cout << "Maximum subsequence of length " << k << ": " << maxSubsequence(num, k) << endl;
    33. return 0;
    34. }
    Advertisement
    Add Comment
    Please, Sign In to add comment
    Public Pastes
    We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
    Not a member of Pastebin yet?
    Sign Up, it unlocks many cool features!

    AltStyle によって変換されたページ (->オリジナル) /