To maximize , we need to stay as close to as possible while reducing the digit sum. The most efficient way is:
Traverse the digits of from right to left (least significant to most significant).
Find the first non-zero digit.
Decrease that digit by .
If n = 1230, the rightmost non-zero digit is .
Decrease it by 1 \to v = 1220.
S(1230) = 6, while S(1220) = 5.
Minimal Reduction: By changing the rightmost non-zero digit, we are subtracting the smallest possible value (the smallest power of ) that actually reduces the digit sum.
Maximality: Any number such that v < x < n would have to keep all digits to the left of our changed position the same. Since the digits to the right of our changed position in were all , any in that range would require at least one of those s to become a larger digit, which would make S(x) \ge S(n).
Sum Change: This operation always results in S(v) = S(n) - 1, which is the closest possible sum to the original.
Time Complexity: O(\log(\max N))
#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;
}