FindMaxLessSum#12381

FindMaxLessSum (Editorial)

Approach

To maximize , we need to stay as close to as possible while reducing the digit sum. The most efficient way is:

  1. Traverse the digits of from right to left (least significant to most significant).

  2. Find the first non-zero digit.

  3. Decrease that digit by .

Example


Why does this work?

#include <bits/stdc++.h>
using namespace std;

void solve() {
    int n ;
    cin >> n ;
    vector <int> a ;
    while(n) {
      a.push_back(n % 10) ;
      n /= 10 ;
    }
    int k = (int) a.size() ;
    for(int i = 0 ; i < k ; i ++) {
      if(a[i]) {
        a[i] -- ;
        break ;
      }
    }
    int ans = 0 ;
    int p = 1 ;
    for(int i = 0 ; i < k ; i ++) {
      ans += a[i] * p ;
      p *= 10 ;
    }
    cout << ans << endl ;
    
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    // freopen("output.txt", "w", stdout);
    // freopen("input.txt", "r", stdin);
    int t ;
    cin >> t ;
    while(t --) {
        solve() ;
    }
    return 0;
}