Alex_tz307

K digits optimal removal

Sep 12th, 2020
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. void optimalDigitsRemoval(const string& s, int K) {
  2.     vector < int > freq(10);
  3.     int N = s.size(), stop = N;
  4.     for(int i = 0; i < N; ++i) {
  5.         int cif = s[i] - '0';
  6.         for(int j = 0; j < cif; ++j)
  7.             if(K >= freq[j]) {
  8.                 K -= freq[j];
  9.                 freq[j] = 0;
  10.             }
  11.             else {
  12.                 freq[j] -= K;
  13.                 K = 0;
  14.             }
  15.         if(K == 0) {
  16.             stop = i;
  17.             break;
  18.         }
  19.         ++freq[cif];
  20.     }
  21.     if(K > 0) {
  22.         for(int i = 0; i < 10 && K > 0; ++i)
  23.             if(K >= freq[i]) {
  24.                 K -= freq[i];
  25.                 freq[i] = 0;
  26.             }
  27.             else {
  28.                 freq[i] -= K;
  29.                 K = 0;
  30.             }
  31.     }
  32.     for(int i = 9; i >= 0; --i)
  33.         for(int j = 0; j < freq[i]; ++j)
  34.             cout << i;
  35.     for(int i = stop; i < N; ++i)
  36.         cout << s[i];
  37. }
Advertisement
Add Comment
Please, Sign In to add comment