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:
def myAnswer(N:int)->int:
   length = len(str(N))
   if(length == 1): return N
   l = list(str(N))
   tmp = 0
   for n in l[1:]:
      tmp += int(n)
   total = length * 9
   if(tmp == total - 9):
      return tmp + int(l[0])
   else:
      total += -9 + int(l[0]) - 1
      return total
def modelAnswer():
   tmp=1
def main():
   N = int(input())
   print(myAnswer(N))

if __name__ == '__main__':
   main()

Submission status: Accepted

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

# A - Digit Sum 2
def digit_sum(str_num):
	sum = 0	
	
	for i in range(len(str_num)):
		sum += int(str_num[i])
	
	return sum


N = input()
patterns = [N]

for i in range(len(N)-1):
	if N[i] != '0':
		left, right = '', ''  
				
		if i > 0:
			left = N[:i]
		
		n = int(N[i]) - 1
		
		if i < len(N) - 1:
			right = '9' * (len(N)-i-1) 
		
		patterns.append(left + str(n) + right)

ans = 0

for p in patterns:
	ans = max(ans, digit_sum(p))
	
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
str_n = str(n)
n_1 = str_n[0]
tmp = int(n_1+"9"*(len(str_n)-1))
ans = int(n_1) + 9*(len(str_n)-1)

if n == tmp:
    print(ans)
else:
    print(ans-1)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil
    #from operator import itemgetter

    #inf = 10**17
    #mod = 10**9 + 7

    n = input().rstrip()
    def digsum(n):
        res = 0
        while n:
            res += n%10
            n //= 10
        return res
    if len(n)==1:
        print(n)
    else:
        if n.count('9')==len(n):
            print(9*len(n))
        elif n.count('9')==len(n)-1 and n[0]!='9':
            print(digsum(int(n)))
        else:
            print(9*(len(n)-1)+int(n[0])-1)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
f, *n = str(int(input())+1)
print(int(f) + 9*len(n) - 1)

Submission status: Accepted

Solution code:
N = int(input())
if set(list(str(N))) == {"9"}:
    print(9 * len(str(N)))
elif N < 10:
    print(N)
elif set(list(str(N)[1:])) == {"9"}:
    print(int(str(N)[0]) + 9 * len(str(N)[1:]))
else:
    print(9 * (len(str(N)) - 1) + int(str(N)[0]) - 1)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = input()
Dig = len(N)
num = None
if Dig == 1:
    print(N)
else:
    for i in range(Dig-1):
        if N[i+1] != str(9):
            num = i
            break
        else:
            continue
    list_num = list(N)
    if not num == None:
        target = int(list_num[num]) -1
        array = list(map(int,N))
        ans = sum(array[:num]) + target + 9*(Dig-num-1)
        print(ans)
    else:
        array = list(map(int,N))
        print(sum(array))

Submission status: Accepted

Solution code:
N = list(map(int, list(input())))
# print(N)
intN = int("".join(list(map(str, N))))
sumN = sum(N)

for x in range(len(N)):
    if x == 0:
        N[x] = N[x] - 1
    else:
        N[x] = 9
intN2 = int("".join(list(map(str, N))))
sumN2 = sum(N)
print(max(sumN, sumN2))

Submission status: Accepted

Solution code:
n = str(input())

o = len(n)-1

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import math

def main():
    N = int(input())
    digit = math.floor(math.log10(N))
    c = N // 10**digit
    if N == (1 + c) * 10 ** digit - 1:
        print(9 * digit + c)
    else:
        print(9 * digit + c -1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import math

def main():
    N = int(input())
    digit = int(math.log10(N))
    c = N // (10**digit)
    if N < int(str(c) + '9'*digit):
        print(9 * digit + c -1)
    else:
        print(9 * digit + c)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# from math import factorial,sqrt,ceil,gcd
# from itertools import permutations as permus
# from collections import deque,Counter
# import re
# from functools import lru_cache # 簡単メモ化 @lru_cache(maxsize=1000)
# from decimal import Decimal, getcontext
# # getcontext().prec = 1000
# # eps = Decimal(10) ** (-100)

# import numpy as np
# import networkx as nx
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix
# from scipy.special import comb

# slist = "abcdefghijklmnopqrstuvwxyz"
N = input()

if int(N)>=10:
    size = len(N)
    top = int(N[0])
    ans = (size-1)*9 + top-1
    num = sum(map(int,list(N)))
    ans = max(ans,num)
else:
    ans = int(N)
    
print(ans)
# print(*ans)   # unpackして出力。間にスペースが入る
# for row in board:
#     print(*row,sep="")    #unpackして間にスペース入れずに出力する
# print("{:.10f}".format(ans))
# print("{:0=10d}".format(ans))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N=list(map(int,list(input())))
    for i in range(1,len(N)):
        if N[i]!=9:
            ans=N[0]-1+9*(len(N)-1)
            break
    else:
        ans=N[0]+9*(len(N)-1)
    print(ans)
        

if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import math
n = int(input())
l = int(math.log10(n))
ma = n//10**l
ans = ma+l*9
#print(str(ma)+'9'*l,n)
if int(str(ma)+'9'*l) > n:
    print(ans-1)
else:
    print(ans)

Submission status: Accepted

Solution code:

def myAnswer(N:int)->int:
   K = len(str(N)) #桁数
   if(K == 1):return N
   c = N // 10**(K-1) #最上位の桁の数
   if((c*10**(K-1) + int("9"*(K-1)))<= N):
      return c + 9 *(K - 1)
   else:
      return c + 9 *(K - 1) -1 


def modelAnswer():
   tmp=1
def main():
   N = int(input())
   print(myAnswer(N))

if __name__ == '__main__':
   main()

Submission status: Accepted

Solution code:
x = int(input())
x += 1

ans = 9 * (len(str(x))-1) + int(str(x)[0])-1
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = input()

c = N[0]
ans = int(c) + 9 * (len(N) - 1)
if int(N) < int(c + '9' * (len(N) - 1)):
    ans -= 1
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
import fractions

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
NS = list(str(N))

q, mod = divmod(N, 10)
i = -1
while q:
    if mod < 8:
        NS[i:] = ['9' for i in range(-i)]
        NS[i-1] = str(int(NS[i-1]) - 1)
    i -= 1
    q, mod = divmod(q, 10)

print(sum(map(int, NS)))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

def resolve():
    N = input()
    M = [int(c) for c in N]

    lm=len(M)
    cnt=0
    if lm==1:
        print(M[0])
    elif set(M[1:])=={9}:
        for i in M:
            cnt+=i
        print(cnt)
    else:
        print(9*(lm-1)+M[0]-1)

resolve()

Submission status: Accepted

Solution code:
s = list(input())

for i in range(1,len(s)):
    if s[i] != "9":
        print(int(s[0])-1+9*(len(s)-1))
        exit()
print(int(s[0])+9*(len(s)-1))

Submission status: Accepted

Solution code:
n=input()
kouho1="9"*(len(n)-1)

if(n[1::]==kouho1):
  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:
N = input()
ans = sum(int(n) for n in N)
m = len(N)
if m > 1:
    ans = max(ans, int(N[0]) - 1 + 9*(m-1))
print(ans)

Submission status: Accepted

Solution code:
n = input()
for i in n[1:]:
    if i != '9':
        print((len(n) - 1) * 9 - 1 + int(n[0]))
        exit()
ans = 0
for i in n:
    ans += int(i)
print(ans)

Submission status: Accepted

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

cnt = 0
while N >= 10:
    N //= 10
    cnt += 1
    #print(N)
temp = (N+1) * 10 ** cnt - 1
temp2 = N * 10 ** cnt - 1
#print(temp)
#print(temp2)
if temp == original:
    print(sum(list(map(int, list(str(temp))))))
else:
    print(sum(list(map(int, list(str(temp2))))))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input())
digit=len(str(n))
def su(k):
  t=[int(str(k)[i]) for i in range(len(str(k)))]
  return sum(t)
m=su(n)
for i in range(1,digit):
  m=max(m,su(pow(10,i)*(n//pow(10,i))-1))
print(m)

Submission status: Accepted

Solution code:
# import string
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

def resolve():
    N = input()
    M = [int(c) for c in N]
    lm=len(M)
    NN=int(N)
    if lm==1:
        print(NN)
    else:
        if set(M[1:])=={9}:
            print(M[0]+(lm-1)*9)
        else:

            print(M[0]-1+(lm-1)*9)



resolve()

Submission status: Accepted

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

import sys
input = sys.stdin.readline

def main():
    N = str(int(input()))
    K = len(N)
    c = int(N[0])
    x = sum([int(i) for i in N])
    print(max(c-1+(K-1)*9, x))

if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = input()

if n.count('9') == len(n):
    ans = 9 * len(n)
elif len(n) == 1:
    ans = int(n)
elif n[0] != '9' and n.count('9') == len(n) - 1:
    ans = int(n[0]) + 9 * (len(n) - 1)
else:
    ans = (int(n[0]) - 1) + 9 * (len(n) - 1)

print(ans)

Submission status: Accepted

Solution code:
n = input()

def sumdigits(num):
  cc = 0
  for c in num:
    cc += int(c)
  return cc

if all([s == '9' for s in n]):
  print(9 * len(n))
else:
  print(max(9 * (len(n) - 1) + int(n[0]) - 1, sumdigits(n)))

Submission status: Accepted

Solution code:
N = input()

def digsum(n):
    total = 0
    while n > 0:
        total += n%10
        n /= 10
        n = int(n)
    return total

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

if N[1:].count('9') == len(N)-1:
    print(digsum(int(N)))
    exit()

ans = int(str(int(N[0])-1) + '9'*(len(N)-1))
print(digsum(ans))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# import sys
r = input()
# print(r)
ans = sum(list(map(int, r)))

if r[0] == 1:
    print(max(ans, (len(r)-1)*9))
else:
    print(max(ans, int(r[0])-1+(len(r)-1)*9))

Submission status: Accepted

Solution code:
import sys
r = input()
# print(r)
ans = sum(list(map(int, r)))
# print(ans)
if len(r) == 1:
    print(max(ans, int(r)))
    sys.exit()
if len(str(int(r)+1)) == len(r)+1:
    print(max(ans, len(r)*9))
    sys.exit()
if r[0] == 1:
    print(max(ans, (len(r)-1)*9))
else:
    print(max(ans, int(r[0])-1+(len(r)-1)*9))

Submission status: Accepted

Solution code:
import heapq
from collections import defaultdict, deque
from math import ceil, factorial
from fractions import gcd
import sys

sys.setrecursionlimit(10 ** 7)
INF = float("inf")
MOD = 10 ** 9 + 7

si = lambda: input().strip()
ii = lambda: int(input())
mii = lambda: map(int, input().split())
lmii = lambda: list(map(int, input().split()))
smii = lambda: sorted(map(int, input().split()))


S = si()

digit = len(S)

head, remaining = S[0], S[1:]

ans = int(head) + 9 * (digit-1)
if remaining != '9' * (digit-1):
    ans -= 1

print(ans)

Submission status: Accepted

Solution code:
S = input()
for s in S[1:]:
    if s != '9':
        print(int(S[0]) - 1 + 9 * (len(S) - 1))
        break
else:
    print(sum([int(s) for s in S]))

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_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

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

N = input()

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

Submission status: Accepted

Solution code:
N = input()
ans = 0
ans1 = int(N[0])-1
for i in range(len(N)):
    ans += int(N[i])

for i in range(1, len(N)):
    ans1 += 9
print(max(ans, ans1))

Submission status: Accepted

Solution code:
n = int(input())
ans = -1
for i in range(18):
    for j in range(2, 11):
        m = (10 ** i) * j - 1
        ans += 1
        if m > n:
            print(ans)
            exit()

Submission status: Accepted

Solution code:
n = int(input())
if n <= 8:
    print(n)

else:
    
    sn = str(n)
    num = len(sn)
    if sn[1:] == "9" * (num - 1):
        print(int(sn[0]) + 9 *(num - 1))
    else:
        print((int(sn[0]) - 1) + 9 * (num - 1))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = input()
if len(N) == 1:
  # 1桁の数字
  print(N)
elif all(map(lambda x: x == '9', N[1:])):
  # 下位が全部9の場合
  print(sum(int(n) for n in N))
else:
  # 下位を全部9にする例
    print(9 * (len(N) - 1) + int(N[0]) - 1)

Submission status: Accepted

Solution code:
def digitSum(n):
    digitSum = 0
    while n > 0:
        digitSum += n%10
        n //= 10
    return digitSum

n = input()
length = len(n)

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

Submission status: Accepted

Solution code:
def digitSum(n):
    digitSum = 0
    while n > 0:
        digitSum += n%10
        n //= 10
    return digitSum

n = int(input())
n_str = str(n)

left = 0
right = 0

if n_str[0] == 1:
    left = int("9" * (len(n_str) - 1))
    right = int("1" + left)
else:
    left = int(str(int(n_str[0])-1) + "9" * (len(n_str) - 1))
    right = int(n_str[0] + "9" * (len(n_str) - 1))

if left <= n < right:
    print(digitSum(left))
elif n == right:
    print(digitSum(right))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = input()
lenN = len(N)
print((int(N) - (int(10**(lenN-1))-1))//(10**(lenN-1)) + 9 * (lenN -1))

Submission status: Accepted

Solution code:
#template
def inputlist(): return [int(j) for j in input().split()]
#template
#issueから始める
N = input()
n = len(N)
dp = [[0,0] for _ in range(len(N)+1)]
dp[1][0] = int(N[0])-1
dp[1][1] = int(N[0])
for i in range(2,len(N)+1):
    if int(N[i-1]) != 0:
        dp[i][0] = max(dp[i-1][0]+9,dp[i-1][1]+int(N[i-1])-1)
        dp[i][1] = dp[i-1][1] + int(N[i-1])
    if int(N[i-1]) == 0:
        dp[i][1] = dp[i-1][1]
        dp[i][0] = dp[i-1][0]+9
print(max(dp[n][0],dp[n][1]))

Submission status: Accepted

Solution code:
n = input()
t = n[0] + '0'*(len(n)-1)
t = str(int(t)-1)
r1 = sum(list(int(d) for d in t))
r2 = sum(list(int(d) for d in n))
print(max(r1,r2))

Submission status: Accepted

Solution code:
import math
import fractions
import bisect
import collections
import itertools
import heapq
import string
import sys
import copy
from decimal import *
from collections import deque
sys.setrecursionlimit(10**7)
MOD = 10**9+7
INF = float('inf') #無限大
def gcd(a,b):return fractions.gcd(a,b) #最大公約数
def lcm(a,b):return (a*b) // fractions.gcd(a,b) #最小公倍数
def iin(): return int(sys.stdin.readline()) #整数読み込み
def ifn(): return float(sys.stdin.readline()) #浮動小数点読み込み
def isn(): return sys.stdin.readline().split() #文字列読み込み
def imn(): return map(int, sys.stdin.readline().split()) #整数map取得
def imnn(): return map(lambda x:int(x)-1, sys.stdin.readline().split()) #整数-1map取得
def fmn(): return map(float, sys.stdin.readline().split()) #浮動小数点map取得
def iln(): return list(map(int, sys.stdin.readline().split())) #整数リスト取得
def iln_s(): return sorted(iln()) # 昇順の整数リスト取得
def iln_r(): return sorted(iln(), reverse=True) # 降順の整数リスト取得
def fln(): return list(map(float, sys.stdin.readline().split())) # 浮動小数点リスト取得
def join(l, s=''): return s.join(l) #リストを文字列に変換
def perm(l, n): return itertools.permutations(l, n) # 順列取得
def perm_count(n, r): return math.factorial(n) // math.factorial(n-r) # 順列の総数
def comb(l, n): return itertools.combinations(l, n) # 組み合わせ取得
def comb_count(n, r): return math.factorial(n) // (math.factorial(n-r) * math.factorial(r)) #組み合わせの総数
def two_distance(a, b, c, d): return ((c-a)**2 + (d-b)**2)**.5 # 2点間の距離
def m_add(a,b): return (a+b) % MOD
def print_list(l): print(*l, sep='\n')

def sieves_of_e(n):
    is_prime = [True] * (n+1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i * 2, n+1, i): is_prime[j] = False
    return is_prime

N = str(iin())
sum_N = 0
for n in N:
    sum_N += int(n)

ans = 0
if N[0] != 1: ans = int(N[0])-1
ans += (len(N)-1)*9
print(max(sum_N, ans))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    l = len(str(n))
    v = int(str(n)[0]) + 9 * (l - 1)
    if str(n)[1:] == '9' * (l - 1):
        print(v)
    else:
        print(v-1)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=int(input())
S=str(N)
flag=False #999か判定するフラグ

for i in range(1,len(S)):
    #print(i,S[i])
    if S[i]!="9":
        flag=False
        break
else:
    flag=True

if flag:
    print( int(S[0]) + 9*(len(S)-1) )
else:
    top=int(S[0])-1
    print(top + 9*(len(S)-1))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N=str(input())
L=len(N)
dp=[[0]*2 for _ in range(L)]
dp[0][0]=int(N[0])
dp[0][1]=int(N[0])-1
for i in range(1,L):
  dp[i][1]=max(dp[i-1][0]+max(0,int(N[i])-1),dp[i-1][1]+9)
  dp[i][0]+=(dp[i-1][0]+int(N[i]))
print(max(dp[L-1][0],dp[L-1][1]))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
N = input()
if int(N) < 10:
    print(N)

elif all(map(lambda x: x == '9', N[1:])):
    print(sum(int(n) for n in N))

else:
    str_n = str(N)
    print(9 * (len(str_n) - 1) + int(str_n[0]) - 1)

Submission status: Accepted

Solution code:
ans = 0
a = input()
num_len = len(a)
num = [k for k in a]
for i in range(1,num_len):
  if num[i] != "9":
    num[i-1]= chr(ord(num[i-1])-1)
    for j in range(i,num_len):
      num[j] = "9"
    break
for w in num:
  ans = ans + int(w)
print(ans)

Submission status: Accepted

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


def solve(N: int):
    S = str(N)
    keta = len(S)
    if S[1:].count("9") == keta-1:
        print(9*(keta-1)+int(S[0]))
        return
    
    if keta == 1:
        print(N)
        return

    print(int(S[0])-1+9*(keta-1))

    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    solve(N)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
n_str = str(n)
num = len(n_str)
hikaku = int(str(n_str[0]) + str(9)*(num-1))
atai = int(int(n_str[0]) + int(9)*(num-1))
if n >= hikaku:
    print(atai)
else:
    print(atai-1)

Submission status: Accepted

Solution code:
def main():

    n = int(input())
    list_rev = []
    temp = list(str(n))
    for i in range(len(temp)):
        list_rev.append(int(temp[-i-1]))
    ans = list_rev[0]
    for i in range(1,len(temp)):
        a = list_rev[i] + ans
        b = list_rev[i] - 1 + 9 * i
        ans = max(a,b)
    print(ans)


def digit_int(num, dig):
    str_num = str(num)
    list_num = list(str_num)
    return list_num[-dig]
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def get_digit_sum(n):
    result = 0
    for d in n:
        result += int(d)
    return result


def main():
    n = input()
    answer = str(int(n[0]) - 1) + "9" * (len(n) - 1)
    print(max(get_digit_sum(answer), get_digit_sum(n)))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    N = input()
    t = 0
    l = []
    for i in N:
        t += int(i)
        l.append(t)
    n = len(N)
    for i, v in enumerate(N):
        if int(v) > 0:
            t = max(l[i] - 1 + 9*(n - i - 1), t)
    return t
print(main())

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    n = input()

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

    if int(tmp) > int(n):
        tmp = str(int(n[0]) - 1) + '9' * (len(n) - 1)

    ans = 0
    for s in tmp:
        ans += int(s)

    print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

dp = [[0]*2 for i in range(l+1)]
dp[l] = [0,0]
for i in range(l):
    dp[l-i-1][0] = max(dp[l-i][0]+int(n[l-i-1]), dp[l-i][1]+int(n[l-i-1])-1)
    dp[l-i-1][1] = max(dp[l-i][0]+9, dp[l-i][1]+9)
dp[0][1] = max(dp[1][0]+int(n[0]), dp[1][1]+int(n[0])-1)
print(max(dp[0]))

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()

# for i in range(N):
# while 1:
#     S = str(N)
#     wa = 0
#     for i in range(len(S)):
#         wa += int(S[i])
    

S = str(N)
su = 0
# nine = "9" * (len(S)-1)
# a = "8" + nine
# b = "9" + nine
wa = 0
wa = 9 * (len(S) - 1) 
# if 
# print(wa)
# c = 9 - int(S[0])
# if S.count("9") == len(S):
#     print(9 * len(S))
if S[1:] == (len(S)-1) * "9":
    ans = 9 * (len(S)-1) + int(S[0])
    print(ans)
# elif len(S) == 1:
#     print(N)
else:
    ans = wa + int(S[0]) - 1
    # print(int(a))
    # print(wa)
    print(ans)

Submission status: Accepted

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    S = input()
    N = len(S)
    if N == 1:
        print(S)
    elif all("9" == s for s in S):
        print(N*9)
    elif all("9" == s for s in S[1:]):
        print(int(S[0]) + 9*(N-1))
    elif S[0] == "1":
        print(9*(N-1))
    else:
        print((int(S[0])-1) + 9*(N-1))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = input()
i_N = 0
for i in range(len(N)):
    i_N += int(N[i])
if len(N) == 1:
    print(N)
    exit()
ans = (len(N) - 1) * 9
if N[0] != '9':
    ans += int(N[0]) - 1
else:
    for i in range(1, len(N)):
        if N[i] != '9':
            ans += int(N[i - 1]) - 1
            break
    else:
        ans += 9
if ans > i_N:
    print(ans)
else:
    print(i_N)

Submission status: Accepted

Solution code:
def main():
    S = input()
    N = len(S)
    if all("9" == s for s in S):
        print(N*9)
    elif N == 1:
        print(S)
    elif all("9" == s for s in S[1:]):
        print(int(S[0]) + 9*(N-1))
    elif S[0] == "1":
        print(9*(N-1))
    else:
        print((int(S[0])-1) + 9*(N-1))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=input()
M=int(N[0:2])
L=len(N[2:])*9
K=0
sum=0
for i in range(len(N)):
	sum+=int(N[i])
K=0
if L>0:
	D=M
else:
	D=M+1
for i in range(D):
	j=str(i)
	if len(j)==1:
		K=max(K,(int(j)))
	else:
		K=max(K,(int(j[0])+int(j[1])))
print(max(sum,K+L))

Submission status: Accepted

Solution code:
n = int(input())
c = len(str(n))
if c == 1:
    print(n)
else:
    for i in range(1,11):
        if int(str(i)+"9"*(c-1)) > n:
            print(9*(c-1)+(i-1))
            break

Submission status: Accepted

Solution code:
n=int(input())
s=str(n)
n=len(s)
s=list(s)

for i in range(n):
    if i==n-1:
        if s[-1-i]=='-1' or s[-1-i]=='0':
            s[-1-i]='0'
        continue
    if s[-1-i]=='-1':
        s[-1-i]='0'
    if s[-1-i]=='9':
        continue
    else:
        t=int(s[-1-i-1])-1
        s[-1-i-1]=str(t)
        s[-1-i]='9'

ans=0
for ss in s:
    ans+=int(ss)
print(ans)

Submission status: Accepted

Solution code:
X = input()
check = True
ans = 0
for i, x  in enumerate(X):
    if i > 0 and x != "9":
        check = False
    if i == 0:
        ans += int(x)
    else:
        ans += 9

print(ans if check else ans - 1)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/agc021/tasks/agc021_a

s=list(input())
sm=sum(map(int,s))
n=len(s)
res=int(s[0])-1+9*(n-1)
print(max(res,sm))

Submission status: Accepted

Solution code:
import sys

def solve():
    input = sys.stdin.readline
    N = list(input().strip("\n"))
    DP = [[0, 0] for _ in range(len(N))]
    DP[0][0] = int(N[0])
    DP[0][1] = int(N[0]) - 1
    for i in range(1, len(N)):
        DP[i][0] = DP[i-1][0] + int(N[i])
        DP[i][1] = DP[i-1][1] + 9
        if N[i] != "0": DP[i][1] = max(DP[i][1], DP[i-1][0] + int(N[i]) - 1)
    
    print(max(DP[-1]))
    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
n = str(input())

if int(n) < 10:
    print(n)
    exit()

m = [0 for _ in range(len(n))]
for i in range(len(n)):
    m[i] = int(n[i])

ans = 0
for i in range(len(n)):
    ans += int(n[i])
ans2 = 0
m[-1] = 9
if n[len(n) - 2] != '0':
    m[len(n) - 2] -= 1
else:
    m[len(n) - 3] -= 1
    m[len(n) - 2] = 9
for i in range(len(n)):
    ans2 += m[i]
ans3 = 9 * (len(n) - 1) + (m[0] - 1)
print(max(ans, ans2, ans3))

Submission status: Accepted

Solution code:
N = list(map(int,list((input()))))

if len(N) == 1:
    print(N[0])
elif set(N[1:]) == set([9]):
    print(N[0] + (len(N) - 1) * 9)
else:
    ans = 0
    for i in range(len(N)):
        tmp = sum(N[:i]) + (N[i] - 1) + 9 * (len(N) - 1 - i)
        ans = max(ans, tmp)
    print(ans)

Submission status: Accepted

Solution code:
s = input()
if s[1:].count("9") == len(s)-1:
    print(sum(map(int, s)))
else:
    print(int(s[0])-1 + 9*(len(s)-1))

Submission status: Accepted

Solution code:
n = int(input())
s = str(n)

a = 0
for i in range(len(s)):
    a += int(s[i])

b = int(s[0])-1+(len(s)-1)*9

print(max(a, b))

Submission status: Accepted

Solution code:
N = int(input())

ans = 0
for d in range(10):
    l = len(str(N))
    v = int(str(d) + '9'*(l-1))
    if v <= N:
        ans = d + 9*(l-1)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = input()

def search(digit, isLess):
    if digit >= len(N):
        return 0

    ret = 0
    if isLess:
        ret = max(ret, search(digit + 1, True) + 9)
    else:
        for i in range(int(N[digit])):
            ret = max(ret, search(digit + 1, True) + i)
        ret = max(ret, search(digit + 1, False) + int(N[digit]))
    return ret

ans = search(0, False)
print(ans)

Submission status: Accepted

Solution code:
N = input()
cnt = 0
n = len(N)
flg = 0
if n == 1:
    print(N)
    exit()
for i,d in enumerate(N):
    if int(d) == 9:
        cnt += int(d)
    else:
        if i == 0:
            cnt += int(N[i])-1 
            cnt += 9 * (n-i-1)
            if N[1:] == "9"*(n-1):
                cnt += 1
            break
        else:
            cnt += int(N[i-1])-1 
            cnt += 9 * (n-i-1)
            break
print(cnt)