はまやんはまやんはまやん

hamayanhamayan's blog

Digit Sum 2 [AtCoder Grand Contest 021 A]

https://agc021.contest.atcoder.jp/tasks/agc021_a

解法

https://agc021.contest.atcoder.jp/submissions/2134961

方針として、なるべく9があった方が嬉しいと言うのがある。
例えば、
「2012」なら「1999」が嬉しい
「1111」なら「0999」が嬉しい
「997」なら「899」が嬉しい
 
見てみると、最上位の数を1つ減らして他は9というのが最適。
これを実装する。
コーナーケースがある(AGCだから多分あるだろうので、ちゃんと探す)
「999」なら「999」が嬉しい
そのままが一番嬉しい場合がある。
そのままの方が総和が大きいならこっちを答えとする。

string S;
//---------------------------------------------------------------------------------------------------
void _main() {
    cin >> S;
    int n = S.length();
    
    int ans = 0;
 
    { // 最上位の数を1つ減らして他は9
        int d = S[0] - '0' - 1;
        d += 9 * (n - 1);
        chmax(ans, d);
    }
 
    { // そのまま
        int d = 0;
        fore(c, S) d += c - '0';
        chmax(ans, d);
    }
 
    cout << ans << endl;
}