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: Wrong Answer)

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> Pi;
typedef pair<ll,ll> Pll;

#define Fi first
#define Se second
#define pb(x) push_back(x)
#define sz(x) (int)x.size()
#define rep(i, n) for(int i=0;i<n;i++)
#define repp(i, n) for(int i=1;i<=n;i++)
#define all(x) x.begin(), x.end()

#define geti1(X) scanf("%d",&X)
#define geti2(X,Y) scanf("%d%d",&X,&Y)
#define geti3(X,Y,Z) scanf("%d%d%d",&X,&Y,&Z)
#define geti4(X,Y,Z,W) scanf("%d%d%d%d",&X,&Y,&Z,&W)

#define GET_MACRO(_1,_2,_3,_4,NAME,...) NAME
#define geti(...) GET_MACRO(__VA_ARGS__, geti4, geti3, geti2, geti1) (__VA_ARGS__)

#define INF 7654321
#define IINF 87654321987654321LL
#define MAXV 200500

ll mod = 1e9 + 7;
int N,M;

ll getsum(ll x){
	ll res = 0;
	while( x > 0 ){
		res += x%10;
		x /= 10;
	}
	return res;
}

ll digit(ll x){
	ll res = 0;
	while( x > 0 ){
		res ++ ;
		x /= 10;
	}
	return res;
}

bool chk(ll x){
	while( x > 0 ){
		if( x%10 != 9 ) return false;
		x /= 10;
	}
	return true;
}

int main(){

	ll n; cin >> n;
	ll ans = 0;
	if( n <= 100000 ){
		for(ll i=1;i<=n;i++){
			ans = max(ans, getsum(i));
		}
		printf("%lld\n",ans);
		return 0;
	}

	ll d = digit(n);
	ans = 9 *(d-1);
	
	if ( chk(n) ){
		ans += 9;
		printf("%lld\n",ans);
		return 0;
	}

	while ( n > 0 ){
		if( n / 10 == 0 && n > 0 ){
			ans += (n-1);
		}
		n /= 10;
	}
	printf("%lld\n",ans);
}