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

#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define INF 1000000000000000007
#define pb emplace_back 
#define mx 1e9+2
#define all(s) s.begin(),s.end()
typedef vector<int> vi;
ll ans=0;
int gh[20];
ll dp[20][164][2];
ll getsum(int idx,int n,ll sum,bool flag){
		ans=max(sum,ans);
	if(idx>n)return sum;
	if(dp[idx][sum][flag]!=-1)return dp[idx][sum][flag];
	int limit=9;
	if(!flag)limit=gh[idx];
	ll res=0;
	for(int i=0;i<=limit;i++){
		if(i<limit||flag){
			res+=getsum(idx+1,n,sum+i,true);
		}
		else{
			res+=getsum(idx+1,n,sum+i,false);
		}
	}
	return dp[idx][sum][flag]=res;
}
void solve(){
	string b;
	cin>>b;
	for(int i=0;i<b.size();i++){
		gh[i+1]=b[i]-'0';
	}
	memset(dp,-1,sizeof dp);
  ll r=getsum(1,b.size(),0,0);
   cout<<ans<<"\n";
}

int main(){
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
   int t=1;
  // cin>>t;
     while(t--){
     	solve();
	 }
     return 0;
}