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# (Mono 4.6.2.0) (judge verdict: Accepted)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using static MyIO;


public class A
{
	public static readonly int FALSE = 0;
	public static readonly int TRUE = 1;

	public static void Main()
	{
		long N = GetLong();
		List<int> digits = new List<int>(64);
		long tmp = N;
		while(tmp > 0)
		{
			digits.Add((int)(tmp % 10));
			tmp /= 10;
		}
		digits.Reverse();

		int[,] dp = new int[digits.Count + 1, 2];
		dp[1, FALSE] = digits[0];
		dp[1, TRUE] = digits[0] - 1;
		for(int i = 1; i < digits.Count; i++)
		{
			dp[i + 1, FALSE] = dp[i, FALSE] + digits[i];
			dp[i + 1, TRUE] = dp[i, TRUE] + 9;
			if(digits[i] > 0)
				dp[i + 1, TRUE] = Math.Max(dp[i + 1, TRUE], dp[i, FALSE] + (digits[i] - 1));
		}
		
		Console.WriteLine(Math.Max(dp[digits.Count, FALSE], dp[digits.Count, TRUE]));
	}
}


public static class MyIO
{
	private static string[] args = null;
	private static int num = -1;
	private static int used = -1;

	private static string getArg()
	{
		if(used == num)
		{
			args = Console.ReadLine().Split(' ');
			num = args.Length;
			used = 0;
		}
		return args[used++];
	}

	public static int GetInt(){ return int.Parse(getArg()); }
	public static long GetLong(){ return long.Parse(getArg()); }
	public static double GetDouble(){ return double.Parse(getArg()); }
	public static string GetString(){ return getArg(); }
}