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.15.1) (judge verdict: Accepted)

use std::str::FromStr;
use std::fmt::Debug;
use std::cmp;
#[allow(dead_code)]
fn read_as_vec<T>() -> Vec<T>
where T: FromStr, <T as FromStr>::Err : Debug{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().split_whitespace().map(|c| T::from_str(c).unwrap()).collect()

}

#[allow(dead_code)]
fn read_as_string() -> String{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

fn get_msd(n: u64) -> u64{
    return n.to_string().chars().nth(0).unwrap().to_digit(10).unwrap() as u64;
}

fn is_almost9(n: u64) -> bool{
    let mut n: u64 = n;

    while n/10 > 0{
        if n%10 != 9{
            return false;
        }
        n /= 10;
    }

    return true;
}

fn num_digits(n: u64) -> u64{
    let mut n = n;
    let mut ans = 0;
    while n > 0{
        n /= 10;
        ans += 1;
    }

    return ans;
}

fn main(){
    let n = read_as_vec::<u64>()[0];
    let k = num_digits(n);
    let c = get_msd(n);
    if is_almost9(n){
        println!("{}", c+9*(k-1));
    }else{
        println!("{}", c+9*(k-1)-1);
    }
}