Problem:
Score : 300 points

Problem Statement

Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Constraints

1\leq N \leq 10^{16}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Sample Input 1

100

Sample Output 1

18

For example, the sum of the digits in 99 is 18, which turns out to be the maximum value.

Sample Input 2

9995

Sample Output 2

35

For example, the sum of the digits in 9989 is 35, which turns out to be the maximum value.

Sample Input 3

3141592653589793

Sample Output 3

137

Solution in Rust (1.42.0) (judge verdict: Accepted)

use std::str::FromStr;

fn get_one<T : FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    return s.trim().parse().ok().unwrap();
}

fn get_vec<T : FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    return s.trim().split_whitespace().map(|e| e.parse().ok().unwrap()).collect();
}

fn get_vec_by_lines<T : FromStr>(n : usize) -> Vec<T> {
    let mut v : Vec<T> = Vec::new();
    for _i in 0..n {
        let x : T = get_one();
        v.push(x);
    }
    return v;
}

fn main() {
    let s : Vec<u64> = get_one::<String>().chars().map(|e| e as u64 - '0' as u64).collect();
    let mut falldown = false;
    let mut ans = 0;
    for i in 0..s.len()-1{
        if falldown {
            ans += 9;
        }
        else if s[i+1] != 9 {
            ans += s[i] - 1;
            falldown = true;            
        }
        else if s[i] == 9 {
            ans += 9;
        }
        else if s[i+1] == 9{
            ans += s[i]
        } else {
            ans += s[i] - 1;
            falldown = true;
        }
    }
    if falldown {
        ans += 9;
    }
    else {
        ans += s[s.len()-1];
    }
    println!("{}", ans);
}