Maximize Sum of Digits
Hazrat Ali
Anton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits.
Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them.
The first line contains the positive integer x (1 ≤ x ≤ 1018) — the integer which Anton has.
Print the positive integer which doesn't exceed x and has the maximum sum of digits. If there are several such integers, print the biggest of them. Printed integer must not contain leading zeros.
100
99
48
48
521
499
Solution
#include <bits/stdc++.h>
using namespace std;
vector<int> to_digits(long long num) {
vector<int> digits;
while (num > 0) {
digits.push_back(num % 10);
num /= 10;
}
reverse(digits.begin(), digits.end());
return digits;
}
long long to_number(vector<int>& digits) {
long long num = 0;
for (auto d: digits) {
num = (num * 10) + d;
}
return num;
}
int maximize(vector<int>& digits, int i) {
digits[i]--;
for (int j = i + 1; j < digits.size(); j++) {
digits[j] = 9;
}
return accumulate(digits.begin(), digits.end(), 0);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
long long x;
cin >> x;
vector<int> xd = to_digits(x);
int mx = accumulate(xd.begin(), xd.end(), 0);
long long ans = x;
for (int i = xd.size() - 1; i > -1; i--) {
vector<int> xdi(xd);
int mxi = maximize(xdi, i);
if (mxi > mx) {
mx = mxi;
ans = to_number(xdi);
}
}
cout << ans << "\n";
return 0;
}