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 C++14 (GCC 5.4.1) (judge verdict: Accepted)

#include<bits/stdc++.h>
#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
typedef long long ll;
using namespace std;
#define sz(x) ((int)(x).size())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
#define MEMSET(v, h) memset((v), h, sizeof(v))
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
#define pb push_back
#define mp make_pair
#define y0 y3487465
#define y1 y8687969
#define j0 j1347829
#define j1 j234892
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
const ll INF = 1LL<<58;
 
int main(){
    ll N;
  	cin >> N;
  	ll temp = N;
  	ll num;
  	ll sum = 0;
  	ll count = 0;
  	ll nine;
  	bool nflag = true;
  	while(temp > 0){
      num = temp % 10;
      temp /= 10;
      ++count;
    }
  	temp = N;
  	if(N >= 10){
      while(temp > 0){
        nine = temp % 10;
        sum += nine;
        if(nine != 9 && temp >= 10) {
          nflag = false;
          break;
        }
              	temp /= 10;
      }
      if(nflag){
        cout << sum << endl;
        return 0;
      }
      else{
        sum = 0;
  		if(num == 1) {
      		for(int i = 0; i < count - 1; ++i) sum += 9;
    	}
  		else{
      	sum = num - 1;
      		for(int i = 0; i < count - 1; ++i) sum += 9;
    	}
    }
    }
  	else{
      sum = N;
    }
  	
  	cout << sum << endl;
}