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:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def f(S):
    res = 0
    for s in S:
        res += ord(s)-ord("0")
    return res
def main():
    S=ST()
    print(max(f(S),int(S[0])-1 + 9*(len(S)-1)))
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
lst_N = [int(c) for c in input()]
set_N = set(lst_N)
first = lst_N[0]
left = lst_N[1:]
if len(lst_N) == 1: #1桁
    print(lst_N[0])
elif len(set_N) == 1 and lst_N[0] == 9: #all 9
    print(sum(lst_N))
elif first != 9 and len(set(left)) == 1 and left[0] == 9: #9以外＋残り全部９
    all_nine = "9" * (len(left))
    lst_all_nine = [int(c) for c in all_nine]
    print(first + sum(lst_all_nine))
else:
    all_nine = "9" * (len(lst_N) - 1)
    lst_all_nine = [int(c) for c in all_nine]
    print((first-1) + sum(lst_all_nine))

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline

def main():
    ans = 0
    N = input().rstrip('\n')
    c = int(N[0])
    ans = c + 9*(len(N)-1)
    if N[1:]!='9'*(len(N)-1):
        ans -= 1
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
N = input()
if len(N) == 1:
    print(N)
    sys.exit()

s = 0
for x in N:
    s += int(x)

if N[0] != '9' and '9'*(len(N)-1) == N[1:]:
    print(s)
elif N[0] != '9':
    print((int(N[0])-1) + 9*(len(N)-1))
elif '9'*len(N) == N:
    print(s)
else:
    print((int(N[0])-1) + 9*(len(N)-1))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
X = int(input())
Y = list(map(int, str(X)))
if X >= 10:
  ans = max(sum(Y), Y[0]-1+9*(len(Y)-1))
else:
  ans = X
print(ans)

Submission status: Accepted

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def is_prime(n):
    if n == 1:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True


# ワーシャルフロイド (任意の2頂点の対に対して最短経路を求める)
# 計算量n^3 (nは頂点の数)
def warshall_floyd(d, n):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d


# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
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

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定



# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret


# ここから書き始める
n = input()
m = len(n)
ans1 = 9 * (m - 1)
ans2 = sum([int(i) for i in n])
ans3 = 0
ok = False
for i in range(m):
    x = int(n[i])
    if i == 0:
        if x >= 2:
            ok = True
            ans3 += x - 1
        continue
    if ok:
        ans3 += 9
    else:
        if x >= 1:
            ok = True
            ans3 += x - 1
ans = max(ans1, ans2, ans3)
# print("ans1 =", ans1)
# print("ans2 =", ans2)
# print("ans3 =", ans3)
print(ans)

Submission status: Accepted

Solution code:
n = input()
nt = sum(map(int, n))
a = (len(n)-1)*9 + int(n[0])-1
print(nt if a < nt else a)

Submission status: Accepted

Solution code:
n = list(input())
ans = 0

a = (len(n) - 1) * 9 + int(n[0]) - 1

if a < sum(map(int, n)):
    ans = sum(map(int, n))
else:
    ans = a

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = input()

cnt = sum(list(map(int, N)))
kyuu = (int(len(N))-1) * 9 + int(N[0]) -1
if cnt > kyuu:
    print(cnt)
else:
    print(kyuu)

Submission status: Accepted

Solution code:
import sys
def S(): return sys.stdin.readline().rstrip()
N = S()
if all([n=='9' for n in 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:
N = input()
NN = N
if len(N) == 1:
    print(N)
    exit()
for i in range(1,len(N)):
    if N[i] != '9':
        NN = str(int(N[0])-1)+'9'*len(N[1:])
        break
ans = 0
for nn in NN:
    ans += int(nn)
print(ans)

Submission status: Accepted

Solution code:
n = list(map(int, list(input().strip())))

total = sum(n)

for i in range(len(n)):
    subtotal = 0
    for j in range(i - 1):
        subtotal += n[j]
    subtotal += n[i] - 1
    for k in range(i + 1, len(n)):
        subtotal += 9

    total = max(total, subtotal)

print(total)

Submission status: Accepted

Solution code:
n = int(input())
d = len(str(n))
n_sum = 0
for i in range(d):
    n_sum += int(str(n)[i])
def judge(n):
    for i in range(1, len(n)):
        if n[i] != "9":
            return True
    return False
print(n // (10 ** (d - 1)) - 1 + 9 * (d - 1) if judge(str(n))  else n_sum)

Submission status: Accepted

Solution code:
N = int(input())
S = str(N)
if(len(S) == 1): print(S); exit(0)
for i in range(1, len(S)):
    if(int(S[i]) != 9):
        print(int(S[0]) - 1 + (len(S) - 1) * 9)
        exit(0)
print(int(S[0]) + (len(S) - 1) * 9)

Submission status: Accepted

Solution code:
N = int(input())
S = str(N)
if(len(S) == 1): print(S); exit(0)
if(len(S) == 2): print(max(N // 10 + N % 10, N // 10 - 1 + 9)); exit(0)
for i in range(1, len(S)):
    if(int(S[i]) != 9):
        print(int(S[0]) - 1 + (len(S) - 1) * 9)
        exit(0)
print(int(S[0]) + (len(S) - 1) * 9)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# A - Digit Sum 2

N = input()
digit = len(N)
ans = 0

for i in range(digit):
    ans += int(N[i])
    if i<digit-1 and N[i+1]!='9':
        ans += 9*(digit-1-i)-1
        break

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = input()
ans = 0
for i in range(len(n)):
    tmp = [9]*len(n)
    for j in range(9, -1, -1):
        tmp[i] = j
        s = int(''.join(map(str, tmp)))
        if s <= int(n):
            ans = max(ans, sum(map(int, str(s))))
            break
print(ans)

Submission status: Accepted

Solution code:
N = input()

Nl = len(N)
tmp = N[0] + '9'*(Nl-1)

if int(N) >= int(tmp):
    answer = int(N[0]) + 9*(Nl-1)
else:
    answer = int(N[0])-1 + 9*(Nl-1)
    
print(answer)

Submission status: Accepted

Solution code:
A= input()
if len(A)== 1:
	print(A)
	exit()
length=len(A)
B = "9" * (length-1)
A=int(A)
C=A-int(B)
B=str(int(C/10**(length-1)))+B
B=int(B)
B=list(str(B))
B=list(map(int,B))
print(sum(B))

Submission status: Accepted

Solution code:
# coding: utf-8
import re
import math
from collections import defaultdict
from collections import deque
import itertools
from copy import deepcopy
import random
import time
import os
import queue
import sys
import datetime
from functools import lru_cache
#@lru_cache(maxsize=None)
readline=sys.stdin.readline
sys.setrecursionlimit(2000000)
#import numpy as np
alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(N)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def is_pow(a,b):#aはbの累乗数か
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def bin_(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def get_facs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def next_comb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def get_primes(n,type="int"):
    if n==0:
        if type=="int":return []
        else:return [False]
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def is_prime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=""):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def floor_(n,x=1):
    return x*(n//x)
def ceil_(n,x=1):
    return x*((n+x-1)//x)
    return ret
def seifu(x):
    return x//abs(x)
######################################################################################################
def main():
    A=list(map(int,list(input())))
    ans=max(sum(A),A[0]-1+(len(A)-1)*9)
    print(ans)
main()

Submission status: Accepted

Solution code:
N = list(input())

nup = sorted(N)

if N[1:len(N)+1] == ["9"] * (len(N)-1):
    sum1 = 0
    for i in range(len(N)):
        sum1 += int(N[i])
    print(sum1)

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

Submission status: Accepted

Solution code:
n = list(input())
p = 0
for i in range(1,len(n)):
    if int(n[i]) != 9:
        p = 1
        break
print(int(n[0])- p + 9*(len(n)-1))

Submission status: Accepted

Solution code:
#print#!/usr/bin/env python3
#%% for atcoder uniittest use
import sys
input= lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**9)
def pin(type=int):return map(type,input().split())
def tupin(t=int):return tuple(pin(t))
def lispin(t=int):return list(pin(t))
#%%code
from collections import Counter
def resolve():
    N=list(input())
    a=sum(map(int,N))
    for n in range(1,len(N)):
        t=(N[:n]+[9]*(len(N)-n))
        a=max(a,sum(map(int,t))-1)
    print(a)
        
#%%submit!
resolve()

Submission status: Accepted

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

n = input()
if int(n) >= int(n[0] + '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()
if N[1:] == '9' * (len(N) - 1):
    print(int(N[0]) + (len(N) - 1) * 9)
else:
    print(int(N[0]) - 1 + (len(N) - 1) * 9)

Submission status: Accepted

Solution code:
s=list(input())

memo = []

for i in s:
    memo.append(int(i))

ans = max(sum(memo),(memo[0]-1)+(len(memo)-1)*9)

print(ans)

Submission status: Accepted

Solution code:
N = input()
K = len(N)
c = N[0]
a = 0
for i in range(1,K):
  if N[i] != "9":
    a = 1
if a == 0:
  print(int(c) + 9*(K-1))
else:
  print(int(c) + 9*(K-1)-1)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = input()

s = 0
for each in n:
  s += int(each)

l = int(n[0]) -1 + 9*(len(n)-1)

print(max(s, l))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[19]:


N = int(input())


# In[20]:


k = len(str(N))
if N%(10**(k-1)) == 10**(k-1) - 1:
    print(int(N/(10**(k-1))) + 9*(k-1))
else:
    print(int(N/(10**(k-1))) + 9*(k-1) - 1)


# In[ ]:

Submission status: Accepted

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

main()

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

def resolve():
    n=input()
    keta=len(n)
    saileft=int(n[0])
    if n[1:].count('9')==keta-1:
        print(saileft+(keta-1)*9)
    else:
        print(saileft-1+9*(keta-1))
resolve()

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
n = input()
int_n = int(n)
len_n = len(n)
ans = sum([int(i) for i in n])

for i in range(len_n):
    target = int(n[:i+1][-1]) -1
    if target < 0:
        continue
    tmp_n = n[:i] + str(target) + '9'* (len_n - i - 1)
    tmp_n_ans = sum([int(i) for i in tmp_n])
    ans = max(tmp_n_ans, ans)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
S = list(input())
S = list(map(lambda x: int(x),S))
ans = 0

for i in range(len(S) - 1,0,-1):
  
  if S[i] == 9:
    tmp = sum(S)
  else:
    S[i] = 9
    S[i - 1] -= 1
    tmp = sum(S)
  
  ans = max(tmp,ans)

if len(S) == 1:
  ans = S[0]

print(ans)

Submission status: Accepted

Solution code:
str_n = input()
digits = [int(c) for c in str_n]

if sum(digits[1:]) == 9 * (len(digits) - 1):
    print(sum(digits))
else:
    print(digits[0] + 9 * (len(digits) - 1) - 1)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = 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:
S = input()
N = len(S)

sum_s = 0
for s in S:
  sum_s += int(s)

print(max(sum_s, (N-1)*9 + int(S[0])-1))

Submission status: Accepted

Solution code:
s = input()
n = len(s)
ans = 0

for c in s:
  ans += int(c)

for i in range(n):
  res =0 
  d = int(s[i])
  if d==0:
    continue
  else:
    d -= 1
  for c in s[:i]:
    res += int(c)
  res += d
  res += (n-i-1)*9
  ans = max(ans, res)
print(ans)

Submission status: Accepted

Solution code:
n = input()
ans = 0
accu = 0
for i, j in enumerate(n):
    j = int(j)
    if j>0:
        ans = max(ans, accu+j-1+9*(len(n)-i-1))
    accu += j
ans = max(ans, accu)
print(ans)

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline
MOD = 1000000007

N  = input()[:-1]

if len(N)== 1:
    print(int(N))
elif len(N)  == 2:
    if N[-1] == '9':
        print(int(int(N)/10) + 9)
    else:
        print(int(int(N)/10)-1 + 9)

else:
    res = 0
    if N[0] == '9':
        check = True
        for i in range(0,len(N)):
            if N[i] != '9':
                check = False
        if check:
            res = 9*(len(N))
        else:
            res = 9*(len(N)-1)+8
    else:
        check = True
        for i in range(1,len(N)):
            if N[i] != '9':
                check = False
            if check:
                res = 9*(len(N)-1)+int(N[0])
            else:
                res = 9*(len(N)-1)+int(N[0])-1
    print(res)

Submission status: Accepted

Solution code:
n = input()
if int(n) == (int(n[0])+1) * 10 ** (len(n)-1) - 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()
l = len(N)

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

Submission status: Accepted

Solution code:
n = input()

k = len(n)
j = "9"*(k-1)

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

Submission status: Accepted

Solution code:
N=input()
n=int(N)
N3=[int(x) for x in list(N)]
#n=int(N)
if n<10:
    print(n)
    exit()
else:
    ans=sum(N3)
    for i in range(len(N)-1):
        N2=int(N[:i+1])-1
        
        N1=[int(x) for x in list(str(N2))]
        ans=max(ans,sum(N1)+9*(len(N)-i-1))
    print(ans)

Submission status: Accepted

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def to_bin(x: int) -> str: return format(x, 'b') # rev => int(res, 2)
def to_oct(x: int) -> str: return format(x, 'o') # rev => int(res, 8)
def to_hex(x: int) -> str: return format(x, 'x') # rev => int(res, 16)
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i):
            is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
## libs ##
from itertools import accumulate as acc
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#

def main():
    n = II()
    s = str(n)
    d = len(s)
    maxv = 0
    sumv = int(s[0])+(d-1)*9
    sumc = s[0]+'9'*(d-1)
    if int(sumc) > n:
        sumv -= 1
    print(sumv)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n =input()

#最上位の桁をc,桁数をkとすると、
#c以外が9の場合(ex.49999)はc,9*(k-1)となる
#それ以外の場合、c,9*(k-2),8となる(ex.9995:9989)

c = int(n[0])
k = len(n)
if int(n)<10:
    print(n);exit()
if int(n[1:])==int('9'*(k-1)):
    ans = c+9*(k-1)
else:
    ans = c+9*(k-1)-1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())

def get_first(n):
	return int(str(n)[0])

def check(n):
	# x99..99かどうか
	s = str(n)
	for i in range(1, len(str(n))):
		if str(s[i]) != '9':
			return False
	return True

if check(n):
	res = get_first(n) + 9 * (len(str(n)) - 1)
else:
	res = (get_first(n) - 1) + 9 * (len(str(n)) - 1)

print(res)

Submission status: Accepted

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

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

ans = 0

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

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = input()
m = int(n)
c = n[0]
k = len(n)
tmp = int(c + "9"*(k-1))
ans = int(c) + (k-1)*9
if tmp > m:
    ans = (int(c)-1) + (k-1)*9
print(ans)

Submission status: Accepted

Solution code:
N = input()
c = N[0]
K = len(N)

temp = int(c + "9"*(K-1))
temp_s = sum(int(a) for a in list(str(temp)))

if temp <= int(N):
    print(temp_s)
else:
    print(temp_s - 1)

Submission status: Accepted

Solution code:
N_str = input()
N = int(N_str)
ans = 0
for i in range(len(N_str)):
  cand = 0
  tmp = '9'*i + N_str[i] + '9'*(len(N_str)-i-1)
  if int(tmp) <= N:
    cand = int(tmp)
  else:
    if int(N_str[i]) >= 1:
      tmp = '9'*i + str(int(N_str[i])-1) + '9'*(len(N_str)-i-1)
    if  int(tmp) <= N:
      cand = int(tmp)
  ans = max(ans, sum([int(l) for l in str(cand)]))
print(ans)

Submission status: Accepted

Solution code:
N = int(input())

if N > 9:
    if (N%(int("1" + (len(str(N)) - 1)*"0"))) == int((len(str(N)) - 1) * "9"):
        tmp = list(str(N))
        tmp = [int(item) for item in tmp]
        print(sum(tmp))
    else:
        tmp = list(str(N - (N%(int("1" + (len(str(N)) - 1)*"0"))) - 1))
        tmp = [int(item) for item in tmp]
        print(sum(tmp))
else:
    print(N)

Submission status: Accepted

Solution code:
N = input()
ans = int(N[0])+9*(len(N)-1)
if not all([N[i] == '9' for i in range(1,len(N))]):
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
N=input()
L=len(N)
dp=[[0,0] for _ in range(L+1)]
# dp[i][j]:i桁目まで決まっていて、
# jなら0~9何入れてもよく
# そうでないなら0~int(N[i])までで、
# ここまでの最大値を格納
dp[1]=[int(N[0]),int(N[0])-1]
for i in range(1,L):
    for j in range(2):
        for d in range(10 if j else int(N[i])+1):
            dp[i+1][int(j or d<int(N[i]))]=max(dp[i][j]+d,dp[i+1][int(j or d<int(N[i]))])
print(max(dp[-1]))

Submission status: Accepted

Solution code:
S=input()
dp=[[0 for i in range(len(S))] for j in range(2)]
if len(S)==1:
    print(S)
    exit()
dp[0][0]=int(S[0])
dp[1][0]=int(S[0])-1
for i in range(len(S)-1):
    dp[0][i+1] = dp[0][i]+int(S[i+1])
    dp[1][i+1] = max(dp[0][i]+int(S[i+1])-1,dp[1][i]+9)
print(max(dp[1][len(S)-1],dp[0][len(S)-1]))

Submission status: Accepted

Solution code:
# mv = 0
# for i in range(10**2-1, 10**3+1):
#     ns = 0
#     si = str(i)
#     n = len(si)
#     for j in range(n):
#         ns += int(si[j])
#     mv = max(mv, ns)
#     print(i, mv)

N = input()
ok = True
for i in range(len(N)-1):
    if N[i+1] != '9':
        ok = False

if len(N) == 1:
    print(int(N))
    exit()
ans = 0
if ok:
    for i in range(len(N)):
        ans += int(N[i])
else:
    if N[0] == '1':
        for i in range(len(N)-1):
            ans += 9
    else:
        ans += int(N[0]) - 1
        for i in range(len(N)-1):
            ans += 9

print(ans)

Submission status: Accepted

Solution code:
# もし全部が9なら、9*N
# 一桁目が9以外なら (一桁目-1) + (len(N)-1 * 9)
# 一桁目が9なら　一桁目が8 + len(N)-1 * 9
S = (input())

if S.count("9") == len(S):
    print(len(S)*9)

elif len(S) == 1:
    print(int(S))

elif S.count("9") == (len(S)-1) and (S[0]!="9"):
    print((int(S[0])) + (len(S)-1)*9)

elif S[0] == "9":
    print(8 + ((len(S)-1)*9))
else:
    print((int(S[0])-1) + (len(S)-1)*9)

Submission status: Accepted

Solution code:
import sys
import time
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    N = input()
    L = len(N)
    if L == 1:
        ans = int(N)
    elif set(N[1:]) == {'9'}:
        ans = int(N[0]) + 9*(L-1)
    else:
        ans = (int(N[0])-1) + 9*(L-1)
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def digit_sum(n):
    res = 0
    while n > 0:
        res += n % 10
        n //= 10
    return res


def resolve():
    n = input()
    l = len(n)

    res = 0
    for i in range(l):
        if i == 0:
            res += int(n[i]) - 1
        else:
            res += 9

    res = max(res, digit_sum(int(n)))
    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
# 3:06
s = input()
out = True
for c in s[1:]:
    if c != '9':
        out = False
        break

if out:
    print(int(s[0]) + (len(s) - 1) * 9)
else:
    print(int(s[0]) - 1 + (len(s) - 1) * 9)

Submission status: Accepted

Solution code:
n = input()
A = []
sum = 0
for i in n:
    A.append(i)
    sum += int(i)

if A[0] == '1':
    print(max(sum, (len(A) - 1) * 9))
else:
    print(max(sum, (len(A) - 1) * 9 + int(A[0]) - 1))

Submission status: Accepted

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def main():
    n = input()
    if len(n) == 1:
        print(n)
        exit()
    allnine = True
    for i in range(1,len(n)):
        if n[i] == '9':
            pass
        else:
            allnine = False
    if n[0] == '9' and allnine:
        print(9 * len(n))
        exit()
    if n[0] == '1' and allnine:
        print(1 + (len(n)-1) * 9)
        exit()
    if n[0] != '1' and allnine:
        print(int(n[0]) + (len(n)-1) * 9)
        exit()
    print(int(n[0]) + (len(n)-1) * 9 - 1)

if __name__ == '__main__':
  main()

Submission status: Accepted

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

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

ans=max(ans,val)
print(ans)

Submission status: Accepted

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