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



Sample input:
100


Sample output:
18

Submission status: Accepted

Solution code:
n = list(input())
l = len(n)

for i in range(l):
    n[i] = int(n[i])

score = 0

if l == 1:
    print(n[0])
else:
    if n.count(9) == l:
        score = sum(n)
    elif n.count(9) == l-1:
        if n[0] != 9:
            score += sum(n)
        else:
            score += 8 + 9*(l-1)
    else:
        if n[0] != 9:
            score += n[0]-1 + 9*(l-1)
        else:
            for j in range(l):
                if n[j] != 9:
                    n[j-1] = 8
                    score += 8 + 9*(l-1)
                    break
    print(score)

Submission status: Accepted

Solution code:
def main():
    n = list(input())
    ans = max(int(n[0])-1 + 9*(len(n)-1), int(n[0]), sum(map(int, n)))
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def linput(ty=int, cvt=list):
	return cvt(map(ty,input().split()))

def gcd(a: int, b: int):
	while b: a, b = b, a%b
	return a

def lcm(a: int, b: int):
	return a * b // gcd(a, b)

def dist(x1,y1,x2,y2):
	return abs(x1-x2)+abs(y1-y2)

def main():
	#N = int(input())
	S = input().rstrip()
	
	res = 0
	l,r = 0,0
	for s in S:
		d = int(s)
		l += 9 if r else d-1
		r += d
	
	res = max(l,r)
	print(res)
	#sT = "No Yes".split()
	#print(sT[res])
	

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
n = int(input());
ans = 0;
all9 = 1;
while n//10 > 0 :
    ans += 9;
    if all9 == 1 and (n - n//10*10) < 9 :
        all9 = 0;
    n = n//10;

if all9 == 1 :
    ans = ans + n;
else :
    ans = ans + n - 1;

print(ans);

Submission status: Accepted

Solution code:
N=int(input())
cnt=1
flag=True
while N>=10:
  if N%10!=9:
    flag=False
  N//=10
  cnt+=1
if flag==True:
  ans=N+9*(cnt-1)
else:
  ans=N+9*(cnt-1)-1
print(ans)

Submission status: Accepted

Solution code:
def main():
    a = 0
    b = False
    for i,v in enumerate(input()):
        if i == 0:
            a += int(v)
        else:
            b = int(v) < 9
            a += 9
    print(a-b)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    n = input()[::-1]
    a = 0
    borrow = False
    for i in enumerate(n):
        if i[0] == len(n)-1:
            if borrow:
                a += int(i[1])-1
            else:
                a += int(i[1])
        else:
            if int(i[1]) < 9:
                borrow = True
            a += 9
    print(a)
        
    
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = [int(i) for i in list(input())]
l = len(n)

ans =  max((n[0]-1) + 9*(l-1),sum(n))
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
if n<=9:
  print(n)
else:
  n=str(n)
  x=n[0]
  x=int(x)-1
  if n[1:].count('9')==len(n)-1:
    print(x+1+(len(n)-1)*9)
  else:
    print(x+(len(n)-1)*9)

Submission status: Accepted

Solution code:
N=int(input())
# N=100
n=str(N)
Length=len(n)

l=list(n)

if l[1:]==['9']*(Length-1):
    ans=int(n[0])+9*(Length-1)
else:
    ans=int(n[0])-1+9*(Length-1)

print(ans)

Submission status: Accepted

Solution code:
n = input()
k = len(n)
a = 9 * (k - 1) + int(n[0]) - 1
b = 0
for i in range(k):
  b += int(n[i])
c = 0
m = ''
if k > 2 and n[-2] != '0':
  m = str(int(n))[:k - 2] + str(int(n[-2]) - 1) + '9'
elif k > 2 and n[-2] == '0':
  m = str(int(n) - (int(n[-1]) + 1))
for i in range(len(m)):
  c += int(m[i])
ans = max(a, b, c)
print(ans)

Submission status: Accepted

Solution code:
N = list(input())
num = len(N)
if N.count('9') == num:
    print(9*num)
elif N.count('9') == num-1 and N[0] != '9':
    print(int(N[0])+9*(num-1))
else:
    if num <= 1:
        print(''.join(N))
    else:
        ans = int(N[0])-1
        ans += 9*(num-1)
        print(ans)

Submission status: Accepted

Solution code:
N = list(input())
num = len(N)
if N.count('9') == num:
    print(9*num)
elif N.count('9') == num-1 and N[0] != '9':
    print(int(N[0])+9*(num-1))
else:
    if num <= 1:
        print(''.join(N))
    else:
        ans = int(N[0])-1
        ans += 9*(num-1)
        print(ans)

Submission status: Accepted

Solution code:
n = input()
ans1=sum(int(i)for i in n)
ans2=int(n[0])-1+9*(len(n)-1)
print(max(ans1,ans2))

Submission status: Accepted

Solution code:
Num = str(input())
L = len(Num)
if Num[1:] == '9'*(L-1):
  val = int(Num[0]) + 9*(L-1)
else:
  val = int(Num[0])-1 + 9*(L-1)
print(val)

Submission status: Accepted

Solution code:
N = input()

c = int(N[0])
K = len(N)
ans = c + 9 * (K - 1) - 1
for i in N[1:]:
    if i != "9":
        break
else:
    ans += 1

print(ans)

Submission status: Accepted

Solution code:
N = int(input())

for i in range(17):
    if 10**i <=N <10**(i+1):
        m=i+1
        break

for j in range(0,10):
    if (10**(m-1))*j + 10**(m-1)-1 <=N< (j+1)*(10**(m-1))+10**(m-1)-1:
        a = j
        break

print(a+9*(m-1))

Submission status: Accepted

Solution code:
n = list(map(int, input()))
l = [sum(n)]
for i in range(1, len(n)):
    n[-i] = 9
    n[-i-1] -= 1
    l.append(sum(n)) 
print(max(l))

Submission status: Accepted

Solution code:
N = list(map(int, input()))
nines = []
total = sum(N)
nines.append(total)

for i in range(1, len(N)):
    N[-i] = 9
    N[-i-1] -= 1
    nines.append(sum(N))

print(max(nines))

Submission status: Accepted

Solution code:
N = input()
k = int(N[0]) + 9*(len(N) - 1)
if N[1:] != '9' * (len(N) - 1):
    k -= 1     
print(k)

Submission status: Accepted

Solution code:
N = int(input())
topdigi = int(str(N)[0])
keta = len(str(N))

candidate = int(str(topdigi) + "9" * (keta - 1))

if candidate > N:
    ans = (topdigi - 1) + 9 * (keta - 1)
else:
    ans = topdigi + 9 * (keta - 1)
print(ans)

Submission status: Accepted

Solution code:
N=input()
NL=len(N)
if N[1:]=='9'*(NL-1):
  ans=int(N[0])+9*(NL-1)
else:
  ans=int(N[0])+9*(NL-1)-1
print(ans)

Submission status: Accepted

Solution code:
N = input()
ans = 0

if N[1:] == "9" * (len(N) - 1):
    ans = int(N[0]) + (9 * (len(N) - 1))
else:
    ans = int(N[0]) + 9 * (len(N) - 1) - 1

print(ans)

Submission status: Accepted

Solution code:
def resolve():
    N = int(input())
    NList = list(str(N))
    maxA = eval("+".join(NList))
    maxA = max(maxA, eval(
        "+".join(list(str(int(NList[0]) - 1) + "9" * (len(NList) - 1)))))
    print(maxA)


resolve()

Submission status: Accepted

Solution code:
n=input();print(max(sum(list(map(int,list(n)))),int(n[0])+9*len(n)-10))

Submission status: Accepted

Solution code:
N = input()

# NはK桁
K = len(N)

# 最上位の桁がc
c = int(N[0])

# 最上位の桁以外
d = N[1:]

if "9" * len(d) == d:
    print(c + 9 * (K - 1))
else:
    print(c + 9 * (K - 1) - 1)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
#from decimal import *

def ketawa(x):
	return sum(map(int, list(str(x))))

N = input()

if len(N) == 1:
	print(N)

else:
	print(max(ketawa(N), int(N[0])-1 + 9*(len(N)-1)))

Submission status: Accepted

Solution code:
N = int(input())
x = 9
order = 0
for i in range(16):
    if x > N:
        break
    x = x*10+9
    order = i+1
ans = x
for i in range(10):
    ans -= 10**order
    if  ans <= N:
        break
ret = 0
while True:
    if ans == 0:
        break
    ret += ans % 10
    ans = ans//10
print(ret)

Submission status: Accepted

Solution code:
N = str(input())
l = len(N)
if N[1:] == '9'*(l-1):
  ans = int(N[0]) + 9*(l-1)
else:
  ans = int(N[0])-1 + 9*(l-1)
print(ans)

Submission status: Accepted

Solution code:
s=input()
k=10**(len(s)-1)
#print(s,str(int(s)//k*k-1))
print(sum(map(int,str((int(s)+1)//k*k-1))) if len(s)!=1 else s)

Submission status: Accepted

Solution code:
N = input()
l = len(N)
ans = sum([int(n) for n in N])
ans = max(ans, (int(N[0])-1)+(l-1)*9)
print(ans)

Submission status: Accepted

Solution code:
#-*-coding:utf-8-*-

def digit_sum(n):
    s = str(n)
    array = list(map(int, s))
    return sum(array)

def main():
    n = input()
    digit=len(n)
    nine_numbers=n.find('9')
    limit=0

    if int(n)<=9:
        print(n)

    elif digit==nine_numbers:
        print(9*int(nine_numbers))

    else:
        max_ans = digit_sum(n)
        head=int(n[0])-1
        limit=str(head)+'9'*(digit-1) 
        ans = max(max_ans,digit_sum(limit))
        print(ans)

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(100000)


def main():
    N = input().strip()
    ans = sum([int(n) for n in N])

    for i in range(len(N)-1):
        if N[i] == 0:
            continue
        else:
            ans = max(ans, sum([int(n) for n in N[:i]]) +
                      int(N[i])-1 + 9*(len(N)-i-1))

    return ans


if __name__ == "__main__":
    print(main())

Submission status: Accepted

Solution code:
N = list(input())
if N[1:].count('9') == len(N[1:]):
    print(int(N[0]) + 9 * (len(N) - 1))
else:
    print(int(N[0]) + 9 * (len(N) - 1) - 1)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

N = input()

if len(N) == 1:
	print(N)
else:
	ans1 = 9*(len(N)-1) + int(N[0])-1
	ans2 = sum([int(x) for x in list(N)])
	print(max(ans1, ans2))

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

N = INT()

if N < 10:
	print(N)
	exit()

ans1 = 9*(len(str(N))-1) + int(str(N)[0])-1

ans2 = sum([int(x) for x in list(str(N))])

ans3 = sum([int(x) for x in list(str(N//10*10-1))])

print(max(ans1, ans2, ans3))

Submission status: Accepted

Solution code:
n = input()
l = len(n)
if l == 1:
    print(n)
    quit()
ans = 9 * (l - 1)
if n[1:] == '9' * (l - 1):
    ans += int(n[0])
else:
    ans += int(n[0]) - 1
print(ans)

Submission status: Accepted

Solution code:
import math

N = int(input())

if N < 10:
    print(N)
else:
    ketasu = int(math.log10(N)//1 + 1)
    ans = 9*(ketasu - 1)

    start = [str(4) , str(5)]
    start += [str(9) for _ in range(ketasu - 2)]
    start = int(''.join(map(str, start)))

    if start > N:
        start = [str(9) for _ in range(ketasu-1)]
        start = int(''.join(map(str, start)))

    #print(start)

    for i in range(start,N+1,10**(ketasu - 2)):
        temp_ans = 0
        for j in list(str(i)):
            temp_ans += int(j)

        if temp_ans > ans:
            ans = temp_ans

    print(ans)

Submission status: Accepted

Solution code:
N = input()
res = 9*(len(N)-1)+int(N[0])-1
if str(int(N)+1)[0] != N[0]:
    res += 1
if len(N) == 1:
    res = N
print(res)

Submission status: Accepted

Solution code:
N = input()
ndig = len(N)
ans1 = N[0] + "9" * (ndig - 1)
ans2 = str(int(N[0]) - 1) + "9" * (ndig - 1)
if int(ans1) <= int(N):
    print(sum(int(d) for d in ans1))
else:
    print(sum(int(d) for d in ans2))

Submission status: Accepted

Solution code:
N = int(input())

N2 =str(N)[0]+(len(str(N))-1)*"9"
ans = 0
for n in N2:
    ans+=int(n)
if int(N2) > N:
    ans-=1
print(ans)

Submission status: Accepted

Solution code:
n=list(input())
le=len(n)
if le==1:
  print(int(n[0]))
  exit()
x=list(n)
x.remove(x[0])
if len(set(x))==1 and x[0]=='9':
  key=int(n[0])
  print(9*(le-1)+key)
  exit()
m=list(n)
m.remove(m[-1])
if len(set(m))==1 and m[0]=='9':
  print(9*(le-1)+8)
else:
  key=int(n[0])
  print(9*(le-1)+key-1)

Submission status: Accepted

Solution code:
x=int(input())
y=str(x)
n=len(y)

if y[1:]=="9"*(n-1):
    print(int(y[0])+9*n-9)
else:
    print(int(y[0])-1+9*n-9)

Submission status: Accepted

Solution code:
n=int(input())
t=list(str(n))
cnt=0
for i in range(1,len(t)):
  if t[i]=="9":
    cnt=cnt+1
if cnt==len(t)-1:
  print(int(t[0])+9*cnt)
else:
  print(int(t[0])-1+9*(len(t)-1))

Submission status: Accepted

Solution code:
N=list(input())
n=[int(i) for i in N]
L=len(N)
if L==1:
  print(n[0])
elif n[1:L]==[9]*(L-1):
  print(sum(n))
else:
  print((L-1)*9+n[0]-1)

Submission status: Accepted

Solution code:
import bisect
N = int(input())
if len(str(N)) == 1:
    print(N)
    exit()
L = len(list(str(N)))-1
A = [10**(L)*i+10**(L)-1 for i in range(10)]  
n = bisect.bisect_left(A,N)-1
if N in A:
    n += 1
ans = [int(list(str(A[n]))[i]) for i in range(len(list(str(A[n]))))]
print(sum(ans))

Submission status: Accepted

Solution code:
n=list(input())
x=[]
for i in n:
  x.append(int(i))
out=int(n[0])-1+(len(n)-1)*9

if x[1:]==[9]*(len(n)-1) or len(n)==1:
  out=sum(x)
print(out)

Submission status: Accepted

Solution code:
n=input()
N=int(n)

f=True
c=int(n[0])
if len(n)==1:
	x=N
else:
	for i in range(1, len(n)):
		if int(n[i]) != 9:
			f=False
	
	if f:
		x=c+9*(len(n)-1)
	else:
		x=c+9*(len(n)-1)-1

print(x)

Submission status: Accepted

Solution code:
s = input()

if s[1:].count("9") == len(s)-1:
    print(9*(len(s)-1)+int(s[0]))
else:
    print(9*(len(s)-1)+int(s[0])-1)

Submission status: Accepted

Solution code:
n = input()

if len(n) == 1:
  print(n)
  exit()

if all(x == "9" for x in n[1:]):
  ans = n
else:
  ok = False
  ans = ""
  for i, c in enumerate(n):
    x = int(c)
    if x == 9:
      ans += "9"
    else:
      if ok:
        ans += "9"
      else:
        if i == len(n)-1:
          ans = ans[:-1]
          ans += str(int(n[i-1])-1)
          ans += "9"
        else:
          ans += str(x-1)
      ok = True
t = 0
for c in ans:
  x = int(c)
  t += x

print(t)

Submission status: Accepted

Solution code:
#! /usr/bin/env python3

import sys
import numpy as np
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)

c, *N = str(int(readline())+1)
print(int(c) + 9 *len(N)- 1)

Submission status: Accepted

Solution code:
import sys
import math
import itertools
def I():return int(sys.stdin.readline().replace("\n",""))
def I2():return map(int,sys.stdin.readline().replace("\n","").split())
def S():return str(sys.stdin.readline().replace("\n",""))
def L():return list(sys.stdin.readline().replace("\n",""))
def Intl():return [int(k) for k in sys.stdin.readline().replace("\n","").split()]
def Lx(k):return list(map(lambda x:int(x)*-k,sys.stdin.readline().replace("\n","").split()))

n = L()
n = [int(k) for k in n]
if len(n) == 1:
    print(n[0])
else:
    print(max(sum(n),9*(len(n)-1)+n[0]-1))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)


#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
N = I()
NN = N+0

L = int_log(N,10)
if N == pow(10,L+1)-1:
  print(L*9+9)
  exit()

count_9 = 0
while (NN+1)%10==0:
  count_9 += 1
  NN = int(str(NN)[:-1])

if count_9 == len(str(N))-1:
  print(sum(map(int,list(str(N)))))
else:
  L = int_log(N,10)
  print((count_9+L)*9+(int(str(N)[0])+9)%10)

Submission status: Accepted

Solution code:
n = int(input()) + 1
str1 = str(n)
print(int(str1[0])-1+(len(str1)-1)*9)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    S = input().strip()

    ans = 0
    f = False
    for i, s in enumerate(S):
        if f:
            ans += 9
        elif i == len(S) - 1:
            ans += int(S[i])
        else:
            if S[i + 1] != "9":
                f = True
                ans += int(S[i]) - 1
            else:
                ans += int(S[i])

    print(ans)

    
    

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = input()
digit = len(n)
n = int(n)
ans = (digit - 1) * 9 + n // (10 ** (digit - 1)) - 1
tmp = n - n // (10 ** (digit - 1)) * (10 ** (digit - 1))
if tmp == (10 ** (digit - 1)) - 1:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
n=int(input())+1
str1=str(n)
print(int(str1[0])-1+(len(str1)-1)*9)

Submission status: Accepted

Solution code:
N = int(input())
if N < 10:
    print(N)
else:
    str_N = str(N)
    ### 最上位以外すべて9 の場合はその値が最大値
    for n in str_N[1:]:
        if n != '9':
            ### それ以外は最上位の桁を一つ下げてあと全部9 が一番最大
            print(int(str_N[0]) - 1 + (len(str_N) - 1) * 9)
            break
    else:
        print(int(str_N[0]) + (len(str_N) - 1) * 9)

Submission status: Accepted

Solution code:
X = input()

if X[0] == 1:
	X2 = [9]*(len(X) - 1)
elif X[1:].count("9") == len(X[1:]):
	X2 = X
else:
	tmp = int(X[0])-1
	X2 = [str(tmp)] + ["9"]*(len(X)-1)


print(sum(list(map(int, X2))))

Submission status: Accepted

Solution code:
N = [int(x) for x in input()]

ans = sum(N)

for i in range(len(N)):
    if i == 0:
        N[0] -= 1
    else:
        N[i] = 9

print(max(ans, sum(N)))

Submission status: Accepted

Solution code:
n=str(int(input())+1)
print(sum(map(int,list(str(int(n[0]+'0'*(len(n)-1))-1)))))

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    N = input().strip()
    L = len(N)
    N = int(N)
    s = ''
    ans = 0
    for _ in range(L):
        t = 9
        while int(str(t) + s) > N:
            t -= 1
        s = str(t) + s
        ans += t
    print(ans)    

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = input()
n = len(N)

if n == 1:
  print(N)
elif N[1:] == '9'*(n-1):
  print(9*(n-1)+int(N[0]))
else:
  print(9*(n-1)+int(N[0])-1)

Submission status: Accepted

Solution code:
n=str(input())
cn=sum(map(int,list(n)))

k=len(n)
c=int(n[0])
n=int(n)
if cn==(c+9*(k-1)):
  print(c+9*(k-1))
else:
  print(c+9*(k-1)-1)

Submission status: Accepted

Solution code:
n=input()
if len(n)==1:
    print(int(n))
elif all(i=="9" for i in n[1:]):
    print((len(n) - 1) * 9 + int(n[0]))
elif n[0]!="1" and n[0]!="9" or n[1]=="0":
    print((len(n)-1)*9+int(n[0])-1)
elif n[0]=="1":
    print((len(n)-1)*9)
elif n[0]=="9":
    print((len(n)-1)*9+int(n[1])-1)

Submission status: Accepted

Solution code:
n = list(map(int,input()))
cnt = 0
b = tuple(n)
c = b

for i in n:
    cnt += 1
    if i == 9:
        continue
    else:
        if cnt == len(n):
            cnt -= 1
            n[cnt-1] -= 1
            break
        else:
            if i == 0:
                n[cnt-2] -= 1
                cnt -= 1
                break
            else:
                n[cnt-1] -= 1
                break

for i in range(cnt,len(n)):
    n[i] = 9

if len(n) == 1:
    n = b

if sum(n) >= sum(b):
    print(sum(n))
else:
    print(sum(b))

Submission status: Accepted

Solution code:
S = input()
N = []
for s in S:
  N.append(int(s))

N.reverse()

ans = 0
for i in range(len(N)):
    if i != len(N)-1:
        ans += 9
        if N[i] != 9:
            N[i+1] -= 1
    else:
        ans += N[i]

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
l = len(str(N))

if N <= 9:
    res = N
elif N%10**(l-1) == 10**(l-1)-1:
    res = N//10**(l-1) + 9*(l-1)
else:
    res = (N//10**(l-1) - 1) + 9*(l-1)
print(res)

Submission status: Accepted

Solution code:
N=input()
ans1=sum(int(i)for i in N)
ans2=int(N[0])-1+9*(len(N)-1)
print(max(ans1,ans2))

Submission status: Accepted

Solution code:
N = input()
if N[1:] == (len(N)-1)*'9':
    print(int(N[0]) + (len(N)-1)*9)
else:
    print((int(N[0])-1) + (len(N)-1)*9)

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


def main():
    N = int(input())

    L = len(str(N))
    ans = sum(map(int, str(N)))

    for d in range(L):
        if str(N)[d] == "0":
            continue
        m = sum(map(int, str(N)[:d + 1])) - 1 + 9 * (L - (d + 1))
        if m > ans:
            ans = m

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N=int(input())
a=len(str(N))#aの桁数
if a==1:
    print(N)
    exit()
else:
    ans=9*(a-1)#Nより1桁少ない値での最大値


    
    for i in range(a):
        y=0
        if i==0:
            for j in range(a):
                y+=int(str(N)[j])
            #print(N)
        else:
            x=str(int(str(N)[:a-i])-1)+"9"*i
            if len(x)!=a:
                x="0"*(a-len(x))+x
            for j in range(a):
                y+=int(x[j])
           # print(x,y)
        if ans<y:
            ans=y
print(ans)

Submission status: Accepted

Solution code:
N = input()
if N[1:] == "9" * (len(N) - 1):
    print(int(N[0]) + 9 * (len(N) - 1))
else:
    print((int(N[0]) - 1) + 9 * (len(N) - 1))

Submission status: Accepted

Solution code:
s = input()
g = s[1:]
a = g.replace('9','')
if a == '':
  print(int(s[0])+(len(s)-1)*9)
elif len(s) == 1:
  print(s)
else:
  print(int(s[0])-1+9*(len(s)-1))

Submission status: Accepted

Solution code:
n = input()
if int(n) < 10:
	print(int(n))
	exit()
flag = n[1:] != '9' * (len(n) - 1)
print(int(n[0]) - flag + 9*(len(n) - 1))

Submission status: Accepted

Solution code:
m = int(input())
m = str(m + 1)
n = list(m)

if len(n) >= 2:
    if int(n[0]) >= 2:
        print((len(n) - 1) * 9 + int(n[0]) - 1)
    else:
        print((len(n) - 1) * 9)
else:
    print(int(n[0]) - 1)

Submission status: Accepted

Solution code:
N = input()
if all([n == '9' for n in N]):
  print(9 * len(N))
else:
  print(max(9 * (len(N) - 1) + (int(N[0]) - 1), sum(list(map(int, N)))))

Submission status: Accepted

Solution code:
n = list(input())
s = 0
for a in n:
    s += int(a)

if len(n) >= 2:
    if int(n[0]) >= 2:
        print(max(s, (len(n)-1)*9+int(n[0])-1))
    else:
        print(max(s, (len(n)-1)*9))
else:
    print(int(n[0]))

Submission status: Accepted

Solution code:
def digitsum(n):
    return eval("+".join(str(n)))

n = int(input())
k = str(n)
if (int(k[0])+1)*10**(len(k)-1)-n == 1:
    print(digitsum(n))
else:
    print((int(k[0])-1)+9*(len(k)-1))

Submission status: Accepted

Solution code:
n_=input()
n=int(n_)
l=len(n_)
for i in range(1,17):
    if n+1==(int(n_[0])+1)*10**(l-1):
        ans=0
        while n>0:
            ans+=n%10
            n//=10
        print(ans)
        exit()

n = int(n_[0])*10**(l-1)-1
ans=0
while n>0:
    ans+=n%10
    n//=10
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=str(n)
a=len(s)
b=(int(s[0])+1)*10**(a-1)-1
ans=9*(a-1)+int(s[0])
if n==b:
  print(ans)
else:
  print(ans-1)

Submission status: Accepted

Solution code:
n = int(input())

if n < 10:
    print(n)
else:
    n = str(n)
    l = len(n)
    if n == n[0] + '9'*(l-1):
        print(int(n[0]) + 9 * (l-1))
    else:
        print(int(n[0]) + 9*(l-1) -1)

Submission status: Accepted

Solution code:
N = input()

f = int(N[0])
res = (len(N) - 1) * 9 + f - 1
s = 0
for i in N:
    s += int(i)

print(max(res, s))

Submission status: Accepted

Solution code:
n = int(input())
for i in range(9 * len(str(n)), 0, -1):
    if i <= 9:
        i_min = i
    else:
        i_min = int(str(i % 9) + '9' * (i // 9))
    if i_min <= n:
        print(i)
        exit()

Submission status: Accepted

Solution code:
N = int(input())
N = list(str(N))
for i in range(len(N)):
  N[i] = int(N[i])
if len(N) > 1:
  print(max(N[0]-1 + 9*(len(N)-1),sum(N)))
else:
  print(N[0])

Submission status: Accepted

Solution code:
d = input()

f = int(d[0])
res = (len(d)-1)*9 + f-1
s = 0
for i in d:
    s += int(i)

print(max(res, s))

Submission status: Accepted

Solution code:
n = input()

a = 9*(len(n)-1)

b = 0
for i in n:
	b += int(i)

c = 0
for i in range(len(n)):
	if i == 0:
		c += int(n[i])-1
	else:
		c += 9
print (max(a,b,c))

Submission status: Accepted

Solution code:
s=input()
if len(s) == 1:
  print(s)
else:
  print(max((len(s)-1)*9+int(s[0])-1,sum([int(s[i]) for i in range(len(s))])))

Submission status: Accepted

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
def resolve():
    n = int(input())
    k = len(str(n))
    dp = [0, -INF]

    for c in str(n):
        c = int(c)
        ndp = [-INF, -INF]
        for d in range(10):
            for lt in range(2):
                if not lt and c < d:
                    continue
                nlt = max(lt, c > d)
                ndp[nlt] = max(ndp[nlt], dp[lt] + d)
        dp = ndp

    print(max(dp))
resolve()

Submission status: Accepted

Solution code:
N = [int(i) for i in input()]
a = sum(N)
b = 9 * (len(N) - 1) + N[0] - 1
print(max(a,b))

Submission status: Accepted

Solution code:
n = list(map(int,list(input())))
num = len(n)
ans = sum(n)
ans = max(ans,9*(num-1)+n[0]-1)
print(ans)