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, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, acos, atan, asin
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 STR(): return input()
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 = sys.maxsize
mod = 10 ** 9 + 7

n = INT()
m = [int(i) for i in str(n)]
l = len(m)
dp = [[0, 0] for _ in range(l)]
dp[0][0] = m[0] - 1
dp[0][1] = m[0]
for i in range(1, l):
    dp[i][0] = max(dp[i - 1][0] + 9, dp[i - 1][1] + m[i] - 1)
    dp[i][1] = dp[i - 1][1] + m[i]
print(max(dp[l - 1][0], dp[l - 1][1]))

Submission status: Accepted

Solution code:
s = input()

ans = 0
for c in s:
    ans += ord(c) - ord('0')

ans = max(ans, ord(s[0])-ord('0')-1 + (len(s)-1)*9)
print(ans)

Submission status: Accepted

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

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, acos, atan, asin
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 STR(): return input()
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 = sys.maxsize
mod = 10 ** 9 + 7

n = INT()
m = [int(i) for i in list(str(n))]
l = len(str(n))
dp = [[0, 0] for _ in range(l)]
dp[0][0] = m[0] - 1
dp[0][1] = m[0]
for i in range(1, l):
    dp[i][0] = max(dp[i - 1][0] + 9, dp[i - 1][1] + m[i] - 1)
    dp[i][1] = dp[i - 1][1] + m[i]
print(max(dp[l - 1][0], dp[l - 1][1]))

Submission status: Accepted

Solution code:
ns = input().strip()
d = len(ns)
n = int(ns)
ans = sum(map(int, str(n)))
for i in range(d):
    m = n - n % (10 ** i) - 1
    ans = max(ans, sum(map(int, str(m))))
print(ans)

Submission status: Accepted

Solution code:
N = input()
keta = len(N)
keta_sum = sum(list(map(int, list(N))))

ans = max(int(N[0]) - 1 + 9 * (keta - 1), keta_sum)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = input()
l = len(N)
f9 = True

def digitsum(s):
    result = 0
    S = str(s)
    for d in S:
        result += int(d)

    return result

for i in range(0,8):
    if (str(i) in N[1:l]):
        f9 = False

if (f9):
    print(digitsum(N))
else:
    tmp = str((int(N[0])-1)) + "9"*(l-1)
    print(digitsum(tmp))

Submission status: Accepted

Solution code:
N=str(input())
le=len(N)
ans=0
for i in range(le):
    tm='9'*i;p='9'*(le-i-1)
    for j in range(10):
        res=tm+str(j)+p
        if(int(res)>int(N)):
            continue
        cnt=0
        for k in range(len(res)):
            cnt+=int(res[k])
        ans=max(ans,cnt)
print(ans)

Submission status: Accepted

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

# コーナーケース
if len(N) == 1:
    print(N[0])
    exit()
elif set(N[1:]) == set([9]):
    print(N[0] + (len(N) - 1) * 9)
    exit()

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

print(ans)

Submission status: Accepted

Solution code:
N = list(input())

flg = 0
for i in range(1,len(N)):
    if N[i]=="9":
        continue
    else:
        flg = 1
        break

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

Submission status: Accepted

Solution code:
# Problem A - Digit Sum 2

# input process
N = input()

# initizalization
keta_len = len(N)
keta_list = [[0]*2 for i in range(keta_len+1)] # keta_list[keta][smaller]
keta_list[0][0] = int(N[0])
keta_list[0][1] = int(N[0]) - 1

for i in range(1, keta_len): # keta loop 2桁目から
    for j in range(2): # smaller loop
        n_lim = 0
        if j==1:
            n_lim = 9
        else:
            n_lim = int(N[i])
        cost = keta_list[i-1][j] + n_lim
        keta_list[i][j] = max(keta_list[i][j], cost)

# output process
max_ans = max(keta_list[keta_len-1])
print(max_ans)

Submission status: Accepted

Solution code:
x=input()
a = list(map(int, x))
b =[0]*len(a)
c =[0]*len(a)

b=a
x=sum(b)
y=0

c=a
for i in range(len(a)):
	c=a
	if c[i]>0:
		c[i]=c[i]-1
		for j in range(i+1,len(a)):
			c[j]=9
		if sum(c)>x:
			x=sum(c)
print(x)

Submission status: Accepted

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

Submission status: Accepted

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

def main():
    n = int(input())
    x = digit_sum(n)
    y = digit_sum(10**(len(str(n))-1)-1)
    z = 0
    if str(n)[0] != 1:
        z = digit_sum(int(str(n)[0]) * 10**(len(str(n))-1)-1)
    print(max(x, y, z))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = list(input())

if n[0] != '9':
    if n.count('9') != len(n)-1:
        n[0] = str(int(n[0])-1)
        for i in range(1, len(n)):
            n[i] = '9'

else:
    for i in range(len(n)-1):
        if n[i+1] != '9':
            n[i] = str(int(n[i])-1)
            for j in range(i+1, len(n)):
                n[j] = '9'

ans = 0
for i in range(len(n)):
    ans += int(n[i])
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:
N = int(input())

if len(str(N)) == 1:
    ans = N
else:
    s = list(str(N))
    S = s[1:]
    #print(S)
    #print(['9']*((len(str(N)))-1))
    if S == ['9']*((len(str(N)))-1):
        ans = int(str(N)[0]) + 9 * (len(str(N))-1)
        #print('YYY')
    else:
        ans = int(str(N)[0]) + 9 * (len(str(N))-1) - 1

print(ans)

Submission status: Accepted

Solution code:
N = input()
keta = len(N)
N = list(N)
c = int(N[0])
if all(c=="9" for c in N[1:keta]):
    print(c+9*(keta-1))
else:
    print(c-1+9*(keta-1))

Submission status: Accepted

Solution code:
n = input()
int_n = int(n)
# 解説通り

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

for i in range(1, len(n)):
    if n[i] != '9':
        ans -= 1
        break
print(ans)

Submission status: Accepted

Solution code:
n = input()
int_n = int(n)
# len(n)桁のうち、オール9、もしくは1つを除いて9、が答え候補。候補を全探索

le = len(n)
nines = 10 ** le - 1
if nines == int_n:
    print(le*9)
    exit()

ans = 0

for i in range(le):
    for dif in range(1, 10):
        candi = nines - dif * 10 ** i
        if 9 * le - dif >= ans and candi <= int_n:
            ans = 9 * le - dif

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = input()

l = list(n[1:])

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# A-Digit Sum 2
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:
N = int(input())
N_ = str(N)
n = len(N_)

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

for i in range(1, n):
    if N_[i] != '9':
        break
else:
    ans = int(N_[0]) + 9*(n-1)
    print(ans)
    exit()

ans = int(N_[0])-1 + 9*(n-1)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
l = len(str(n))
a = [int(i) for i in list(str(n))]
'''
b = sum(a)
c = [9 for _ in range(l)]
c[0] = a[0] - 1
d = sum(c)
print(max(b, d))
'''
#桁dpで解く
dp = [[0 for _ in range(l)] for _ in range(2)] #dp[0: 未満, 1: 未満でない][最大の桁和]
dp[0][0] = a[0] - 1
dp[1][0] = a[0]
for i in range(1, l):
    dp[0][i] = max(dp[0][i-1] + 9, dp[1][i-1] + a[i] - 1)
    dp[1][i] = dp[1][i-1] + a[i]
print(max(dp[0][l-1], dp[1][l-1]))

Submission status: Accepted

Solution code:
n=input()

n_keta=0
for i in n:
    n_keta+=int(i)
temp=int(n[0])-1+(len(n)-1)*9
ans=max(n_keta,temp)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

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

print(ans)

Submission status: Accepted

Solution code:
n = list(map(int, list(input()[::-1])))
l = len(n)

ans = dec = 0
for i in range(1<<l):
        cnt = 0
        for j in range(l):
                if j==l-1:
                        cnt += n[j] - dec
                        break
                if((i>>j)&1):
                        cnt += 9
                        dec = True
                else:
                        cnt += n[j] - dec
                        dec = False
        ans = max(ans, cnt)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
l = len(str(n))
a = [int(i) for i in list(str(n))]
b = sum(a)
c = [9 for _ in range(l)]
c[0] = a[0] - 1
d = sum(c)
print(max(b, d))

Submission status: Accepted

Solution code:
S=input()
N=int(S)
k=len(S)

dp = [[-1] * 2 for _ in range(k+1)]
dp[0][0] = 0
for i in range(k):
    c = int(S[i])
    dp[i+1][0] = dp[i][0] + c
    dp[i+1][1] = dp[i][1]
    if dp[i][1] >= 0:
        dp[i+1][1] = max(dp[i+1][1], dp[i][1] + 9)
    if c >= 1:
        dp[i+1][1] = max(dp[i+1][1], dp[i][0] + c-1)

print(max(dp[k][0], dp[k][1]))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input())
m=int(n)
cnt=int(0)
while m>9:
    m//=10
    cnt+=1
ans=m-1+cnt*9
Ans=int(0)
while n>0:
    Ans+=n%10
    n//=10
print(int(max(Ans,ans)))

Submission status: Accepted

Solution code:
n=input()
if len(n)==1:
    print(int(n))
elif n[1:].count("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:
N=input()
b=0
count=0
if len(N)==1:
    print(N)
else:
    if (len(set(N[1:]))==1)and(N[1]=="9"):
        print(int(N[0])+9*(len(N)-1))
    else:
        print(int(N[0])-1+9*(len(N)-1))

Submission status: Accepted

Solution code:
n = int(input())

l = len(str(n))
# if n < 10:
#     ans = n
# else:
ans1 = 9 * (l-1) + int(str(n)[0]) - 1
ans2 = sum([int(x) for x in list(str(n))])
ans = max(ans1, ans2)
# print(ans1, ans2)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())

l = len(str(n))
if n < 10:
    ans = n
else:
    ans1 = 9 * (l-1) + int(str(n)[0]) - 1
    ans2 = sum([int(x) for x in list(str(n))])
    ans = max(ans1, ans2)
print(ans)

Submission status: Accepted

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

n = int(input())
n = str(n)
ans = (len(n) - 1) * 9 + int(n[0])

for i in range(1, len(n)):
  if int(n[i]) != 9:
    ans -= 1
    break
    
print(ans)

Submission status: Accepted

Solution code:
N=input()
nums=[int(N[0]), int(N[0])-1]
for i in range(1, len(N)):
  nums=[nums[0]+int(N[i]), max(nums[1]+9, nums[0]+int(N[i])-1)] if N[i]!='0' else [nums[0]+int(N[i]), nums[1]+9]
print(max(nums))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
S=input()
N=list(map(int, S))
DP=[[-1]*2 for _ in range(len(N)+1)]
DP[0][0]=0
for i in range(len(N)):
    for j in range(2):
        if DP[i][j] < 0:
            continue
        for k in range(10):
            ni=i+1
            nj=j
            if j==0:
                if k < N[i]:
                    nj=1
                elif k > N[i]:
                    continue
            DP[ni][nj]=max(DP[ni][nj],DP[i][j]+k)
print(max(DP[len(N)]))

Submission status: Accepted

Solution code:
s = input()
digit = len(s)

first_num = int(s[0])
a = 0
a = 9*(digit-1) + int(s[0]) - 1

b = 0
for i in s:
    b += int(i)
print(max(a, b))

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    if N < 10:
        print(N)
    elif str(N)[1:] == "9"*(len(str(N))-1):
        print(sum(list(map(int,list(str(N))))))
    else:
        ans = sum([9]*(len(str(N))-1))
        if int(str(N)[0]) >= 2:
            ans += int(str(N)[0])-1
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())

l = len(str(n))
top = n // (10**(l-1))

s = 0
for i in range(l):
	s += int(str(n)[i])

if top == 1:
	print(max(9 * (l - 1), s))
else:
	print(max(top - 1 + 9 * (l - 1), s))

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:
m=input()
a=int(m[0])-1+(len(m)-1)*9
b=0
for i in m:
  b+=int(i)
print(max(b,a))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def all_nine_check(num):
    for i in range(1, len(num)):
        if num[i] == '9':
            pass
        else:
            return False
    return True

n = input()
if all_nine_check(n):
    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:
#!/usr/bin/env python3
s = input()
digit = len(s)
if s[1:] == "9"*(digit-1):
    print(int(s[0])+9*(digit-1))
else:
    print(int(s[0])+9*(digit-1)-1)

Submission status: Accepted

Solution code:
def digit_sum2(num):
    total = 0
    for digit in str(num):
        total += int(digit)
    return total
    
n = input()
l = len(n)
n = int(n)

print(max(digit_sum2(n), n // (10 ** (l-1)) - 1 + 9 * (l-1)))

Submission status: Accepted

Solution code:
def digit_sum2(num):
    total = 0
    for digit in str(num):
        total += int(digit)
    return total
    
n = input()
l = len(n)
n = int(n)

if n == 10 ** l -1:
    print( 9 * l )
elif 1 <= n <= 9:
    print(n)
else:
    print(max(digit_sum2(n), n // (10 ** (l-1)) - 1 + 9 * (l-1)))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
N=int(input())

if len(str(N))==1:
    ans=N
else:
    
    if 1==len(set(list(str(N))[1:])) and int(str(N)[1])==9:
        ans=9*(len(str(N))-1) + int(str(N)[0])
    else:
        ans=9*(len(str(N))-1) + int(str(N)[0])-1

print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
N = int(input())
l = len(str(N))
ans = 0
for i in range(1, 10):
    if N >= int("{}{}".format(i, "9"*(l-1))):
        ans = max(ans, 9*(l-1) + i)
if ans == 0:
    ans = 9 * (l-1)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
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 operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n=ii()
ns=list(str(n))
if len(ns)==1:
    print(n)
    exit()
#print(ns[1:])
if int("".join(ns[1:])) == int("".join([str(9)]*(len(ns)-1))):
    print(int(ns[0])+9*(len(ns)-1))
else:
    print(int(ns[0])+9*(len(ns)-1)-1)

Submission status: Accepted

Solution code:
n=str(input())
m=len(n)
sum=0
for i in range(m):
    sum+=int(n[i])
if m==1:
    print(n)
elif list(set(n[1:]))==['9']:
    print(sum)
else:
    print(9*(m-1)+int(n[0])-1)

Submission status: Accepted

Solution code:
N = int(input())
S = str(N)
M = len(S)
dp = [[-1*10**9 for i in range(2)] for j in range(M + 1)]
dp[0][1] = 0
for i in range(M):
    for d in range(10):
        if d < ord(S[i]) - 48:
            dp[i + 1][0] = max(dp[i + 1][0], dp[i][0] + d, dp[i][1] + d)
        elif d == ord(S[i]) - 48:
            dp[i + 1][0] = max(dp[i + 1][0], dp[i][0] + d)
            dp[i + 1][1] = max(dp[i + 1][1], dp[i][1] + d)
        else:
            dp[i + 1][0] = max(dp[i + 1][0], dp[i][0] + d)

print(max(dp[M]))

Submission status: Accepted

Solution code:
def main():
    from itertools import dropwhile

    S = input()
    it = dropwhile(lambda char: char == '9', reversed(S))
    # 末尾から見て9以外の数字が現れたら、以降をiterate

    len_ = len(list(it))
    if len_ <= 1:
        print(sum(map(int, S)))
    else:
        head = S[0]
        body = str(int(head) - 1)
        body += '9' * (len(S) - 1)

        print(sum(map(int, body)))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math

def digit(n):
    return len(str(n))

def digitsum(n):#nは正の整数、各位の和、許容は１０＾１０００
    if n<10:
        return n
    else:
        m=n//10
        return n%10+digitsum(m)

def maxdigit(N):
    if digit(N)==1:
        return N
    else:
        return max([9*(digit(N)-1)+int(str(N)[0])-1,digitsum(N)])

N=int(input())
print(maxdigit(N))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [input() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [int(input()) for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def roundUp(a, b):
        return -(-a // b)

    @staticmethod
    def toUpperMultiple(a, x):
        return Math.roundUp(a, x) * x

    @staticmethod
    def toLowerMultiple(a, x):
        return (a // x) * x

    @staticmethod
    def nearPow2(n):
        if n <= 0:
            return 0
        if n & (n - 1) == 0:
            return n
        ret = 1
        while(n > 0):
            ret <<= 1
            n >>= 1
        return ret

    @staticmethod
    def sign(n):
        if n == 0:
            return 0
        if n < 0:
            return -1
        return 1

    @staticmethod
    def isPrime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True


class PriorityQueue:
    def __init__(self, l=[]):
        self.__q = l
        heapq.heapify(self.__q)
        return

    def push(self, n):
        heapq.heappush(self.__q, n)
        return

    def pop(self):
        return heapq.heappop(self.__q)


MOD = int(1e09) + 7
INF = int(1e15)


def calc(N):
    return sum(int(x) for x in str(N))


def main():
    # sys.stdin = open("sample.txt")
    N = Scanner.int()

    ans = calc(N)
    ans = max(ans, calc(int(str(int(str(N)[0])-1) + "9" * (len(str(N)) - 1))))
    ans = max(ans, calc(max(0, N - N % 10 - 1)))
    print(ans)
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = input()
n = 0
for i in range(1,len(N)):
	if(N[i] == "9"):
		n+=1
if(n==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:
N=input()
if(N[1:len(N)].count("9")!=len(N)-1):
    print(int(N[0])-1+9*(len(N)-1))
else:
    print(int(N[0])+9*(len(N)-1))

Submission status: Accepted

Solution code:
n = input()

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

Submission status: Accepted

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

m = str(int(s[0]) - 1) + (len(s) - 1) * "9" 
ans1 = 0
for i in range(len(m)):
    ans1 += int(m[i])

if s[-1] != "9" and n >= 10:
    n1 = n - (int(s[-1]) + 1)
    s = str(n1)

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

print(max(ans1, ans2))

Submission status: Accepted

Solution code:
n = input()
l = len(n)
def su(x):
	return sum([int(i) for i in str(x)])
ans = su(n)
for j in range(1,l):
	pre = su(int(n[:j])-1)
	suf = (l-j)*9
	ans = max(ans,pre+suf)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
s = input()
l = len(s)
if l == 1:
	ans = int(s)
elif s[1:].count("9") == l-1:
	ans = int(s[0]) + 9 * (l-1)
else:
	ans = (l-1)*9 + (int(s[0])-1)

print(ans)

Submission status: Accepted

Solution code:
N = input().strip()
n = len(N)
cntmax = 0
for i in range(n):
    cntmax += int(N[i])
for j in range(n-1):
    x=N[:j]
    if N[j]!="0":
        x += str(int(N[j])-1)+"9"*(n-1-j)
        cnt = 0
        for i in range(n):
            cnt += int(x[i])
        cntmax = max(cntmax,cnt)
print(cntmax)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = 1e10

#solve
def solve():
    n = II()
    if str(n + 1)[0] != str(n)[0]:
        print(sum(map(int, list(str(n)))))
    else:
        print(int(str(n)[0]) + (len(str(n)) - 1) * 9 - 1)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
if sys.platform in (['ios','darwin','win32']):
	sys.stdin=open('Untitled.txt')
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return [int(s) for s in input().split()]

def main():
	N = INT()
	S = [int(s) for s in str(N)]
	# print(S)

	A = []
	smaller = False
	for i in range(len(S)-1):
		if smaller:
			A.append(9)
		else:
			if S[i] == 9 and S[i+1] == 9:
				A.append(9)
			elif S[i+1] == 9:
				A.append(S[i])
			else:
				smaller = True
				A.append(S[i]-1)

	if smaller: A.append(9)
	else: A.append(S[-1])

	# print(A)
	print(sum(A))

if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
N = input()

tmp = 0
for n in N:
	tmp+=int(n)
	
ans = max(
	int(N[0])-1 + (len(N)-1) * 9,
	tmp
	)

print(ans)

Submission status: Accepted

Solution code:
def func(S):
   if len(S)==1:
      return int(S)
   else: 
      flag=True  
      for i in range(1,len(S)):
         if S[i]!="9":
            flag=False
      
      if flag==False:
         S_0=max(0,int(S[0])-1)
         S_list=[S_0]
         for i in range(1,len(S)):
            S_list.append(9)
         return sum(S_list)
      
      else:
         S_list=list(map(int,[c for c in S]))
         return sum(S_list)

S=input()
total=func(S)
print(total)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
A = []
while N != 0:
  A.append(N%10)
  N //= 10
n = len(A)
nine = 0
for i in range(n-1):
  if A[i] == 9:
    nine += 1
if nine == n - 1:
  print(sum(A))
else:
  for i in range(n-1):
      A[i] = 9
  if A[n-1] > 1:
    A[n-1] -= 1
    print(sum(A))
  else:
    print(sum(A[i] for i in range(n-1)))

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from functools import lru_cache

N = int(readline())

@lru_cache(None)
def F(N):
    if N < 10:
        return N
    q,r = divmod(N,10)
    x = F(q) + r
    y = F(q-1) + 9
    return max(x,y)

answer = F(N)
print(answer)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def dgsm(n):
    ans=0
    while n>0:
        ans+=n%10
        n//=10
    return(ans)
n=input()
if len(n)==1:
    print(n)
    exit()
ans=True
for i in range(1,len(n)):
    if n[i]!="9":
        ans=False
if ans:
    print(int(n[0])+(len(n)-1)*9 )
    exit()
print((len(n)-1)*9+int(n[0])-1)

Submission status: Accepted

Solution code:
N = input()

ans = int(N[0])
ans += 9*(len(N)-1)
if len(N) - 1 != N[1:].count("9"):
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
n = input().zfill(16)
def main(n):
    len_n = len(n)
    INF = 10**18
    memo_ls = [[0 for i in range(2)] for j in range(len_n+1)]
    memo_ls[0][0] = 0
    memo_ls[0][1] = -INF
    for i in range(1, len_n+1):
        s = int(n[i-1])
        memo_ls[i][0] = memo_ls[i-1][0] + s
        memo_ls[i][1] = memo_ls[i-1][1] + 9
        if s > 0:
            memo_ls[i][1] = max(memo_ls[i][1], memo_ls[i-1][0] + s - 1)
    print(max(memo_ls[-1]))
    return 0

main(n)

Submission status: Accepted

Solution code:
N = input()

ret = max(sum(int(n) for n in N), int(N[0]) - 1 + 9 * (len(N) - 1))
print(ret)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10000000)
INF = 1<<32


def solve(N: int):
    sn = str(N)
    if sn[1:] == '9'*(len(sn)-1):
        print(int(sn[0])+9*(len(sn)-1))
    else:
        print(int(sn[0])+9*(len(sn)-1)-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 = input()
suma = 0
for i in N:
    suma += int(i)
c = False
for i in range(9):
    if str(i) in N[1:]:
        c = True
if c:
    print(9*(len(N)-1) + (int(N[0])-1))
else:
    print(9*(len(N)-1) + int(N[0]))

Submission status: Accepted

Solution code:
N = input()
suma = 0
for i in N:
    suma += int(i)

c = False
for i in range(9):
    if str(i) in N[1:]:
        c = True
if c:
    print(9*(len(N)-1) + (int(N[0])-1))
else:
    print(9*(len(N)-1) + int(N[0]))

Submission status: Accepted

Solution code:
N = input()
suma = 0
for i in N:
    suma += int(i)
if N[0] == '1':
    c = False
    for i in range(9):
        if str(i) in N[1:]:
            c = True
    if c:
        print(9*(len(N)-1))
    else:
        print(9*(len(N)-1)+1)
else:
    c = False
    for i in range(9):
        if str(i) in N[1:]:
            c = True
    if c:
        print(9*(len(N)-1) + (int(N[0])-1))
    else:
        print(9*(len(N)-1) + int(N[0]))

Submission status: Accepted

Solution code:
N=int(input())
L=len(str(N))
ans=(L-1)*9
ans+=int(str(N)[0])
tmp=[str(N)[0]] + ["9"]*(L-1)
tmp=int("".join(tmp))
if tmp>N:
  ans-=1
print(ans)