fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Function to generate the maximum possible number
  5. string getLargestNumber(string num) {
  6. int N = num.length();
  7. string ans = "";
  8. vector<int> freq(10);
  9. int left = 0;
  10.  
  11. // Two-pointer technique to find windows of same parity consecutive elements
  12. while (left < N) {
  13. int right = left;
  14.  
  15. // Find a window of consecutive elements with the same parity
  16. while (right < (N - 1) && (num[right] - '0') % 2 == (num[right + 1] - '0') % 2) {
  17. ++freq[num[right] - '0'];
  18. right++;
  19. }
  20.  
  21. // Add the last element of the window
  22. ++freq[num[right] - '0'];
  23.  
  24. // Add elements in descending order for the current window
  25. for (int i = 9; i >= 0; i--) {
  26. while (freq[i] > 0) {
  27. ans += to_string(i);
  28. --freq[i];
  29. }
  30. }
  31.  
  32. // Move to the next window
  33. left = right + 1;
  34. }
  35.  
  36. return ans;
  37. }
  38.  
  39. // Driver function to test getLargestNumber
  40. int main() {
  41. // Test input
  42. string num = "0082663";
  43. cout << getLargestNumber(num) << endl;
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
8662003