Problem:


Score : 300 points

Problem Statement

Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Constraints

1\leq N \leq 10^{16}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Sample Input 1

100

Sample Output 1

18

For example, the sum of the digits in 99 is 18, which turns out to be the maximum value.

Sample Input 2

9995

Sample Output 2

35

For example, the sum of the digits in 9989 is 35, which turns out to be the maximum value.

Sample Input 3

3141592653589793

Sample Output 3

137



Sample input:
100


Sample output:
18

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N= list(str(input()))
import numpy as np
nn = np.array(N).astype(int)
ans = 0
for i in range(1,len(nn))[::-1]:
    if(nn[i] == -1):
        nn[i - 1] -= 1
        nn[i] = 9
    if(9-nn[i] > 0):
        nn[i-1] -= 1
        nn[i] = 9
        ans += 9
    else:
        ans += nn[i]

ans += nn[0]
print(ans)

Submission status: Accepted

Solution code:
def main():
    n = input()
    if len(n) == 1:
        print(n)
        return
    if set(n[1:]) == {'9'}:
        print(int(n[0]) + 9 * (len(n) - 1))
        return

    for i, c in enumerate(n):
        if c != '9':
            print(9 * (len(n) - 1) + int(n[0]) - 1)
            return
    else:
        print(9 * len(n))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = long(raw_input())

if all(map(lambda x: x == '9', str(N)[1:])):
    print(sum(map(int, str(N))))
else:
    print((int(str(N)[0]) - 1) + (len(str(N))-1) * 9)

Submission status: Accepted

Solution code:
N=raw_input()
S=list(N)
init_sum=0
for i in S:
	init_sum+=int(i)

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

if init_sum>n:
	print init_sum
else:
	print n

Submission status: Accepted

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

T=sum(S)

if int(N)<10:
    print(N)
elif 9*(len(S)-1)+S[0]-1 >= T:
    print(9*(len(S)-1)+S[0]-1)
elif S[-1]==9: print(T)
elif S[0]==9: print(9*len(S))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = input()

sum1 = sum(map(int, N))
sum2 = int(N[0]) - 1 + 9 * (len(N) - 1)

print(max(sum1, sum2))

Submission status: Accepted

Solution code:
n=int(input())
li=list(map(int,list(str(n))))
if(n<10):
    print(n)
else:
    ma=sum(li)
    for i in range(0,len(li)-1):
        if(li[-(i+1)]!=9):
            li[-(i+1)]=9
            li[-(i+2)]-=1
        ma=max([ma,sum(li)])
    print(ma)

Submission status: Accepted

Solution code:
tes =input()
a = [int(data) for data in tes] 
no_change = sum(a)
changes = a[0]-1 + (len(a)-1)*9
if changes > no_change:
	print(changes)
else:
	print(no_change)

Submission status: Accepted

Solution code:
N=list(input())
cnt=0
size=len(N)-1
if size==0:
    print(N[0])
    exit()
N.reverse()

for i in range(size):
    if N[i]!="9":
        N[i]="9"
        N[i+1]=str(int(N[i+1])-1)
for i in range(size+1):
    cnt+=int(N[i])
print(cnt)

Submission status: Accepted

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

n = raw_input()
a = len(n)

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

if not int(n) == (int(n[0])+1)*(10**(a-1))-1:
    ans -= 1

print ans

Submission status: Accepted

Solution code:
import sys
import random

def rd():
        return sys.stdin.readline().rstrip()

def rdi():
        return [ int(x) for x in rd().split() ]

n = rdi()[0]

def f(n):
        s = 0
        a = n
        b = 0
        t = ""
        while a >= 10:
                b = a % 10
                a = a / 10
                if b <= 8 and a >= 1:
                        s = s + 9
                        a = a - 1
                        b = 9
                else:
                        s = s + b
                t = str(b) + t
        s += a
        t = str(a) + t
        #print t
        #print s
        return int(t)

#print n
t = f(n)
#print t
s = sum([ int(a) for a in str(t) ])
print s

Submission status: Accepted

Solution code:
s = input()
if int(s) < 10: print(s); exit()

ans = -1
for i in range(len(s)):
    t = s[:i]
    NINE = (len(s)-len(t))
    SUB = 0
    t+= '9' * NINE
    if int(s) < int(t): SUB = int('1' + '0' * NINE)
    t = max(int(t) - SUB, 0)
    ans = max(ans, sum(int(c) for c in str(t)))
print(ans)

Submission status: Accepted

Solution code:
import math
n = int(input())
s = 10**(int(math.log(n,10))+1) - 1
while s>n:
    s -= 10**int(math.log(n,10))
print(sum(list(map(int,list(str(s))))))

Submission status: Accepted

Solution code:
N = int(input())

nn = str(N)

Sum = []
s = 0
for n in nn:
    s += int(n)
Sum.append(s)

for i in range(len(nn)):
    s = 0
    for j,n in enumerate(nn):
        if j < i:
            s += int(n)
        elif j == i:
            s += int(n)-1
        else:
            s += 9
    Sum.append(s)

print(max(Sum))

Submission status: Accepted

Solution code:
N = int(raw_input())

t = len(str(N + 1)) - 1

s = int((N + 1) / (10 ** t)) - 1

print s + 9 * t

Submission status: Accepted

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

leng = len(nums)

for i in range(leng-1):
    index = -1 * (i+1)
    if nums[index] == 9:
        pass
    else:
        nums[index] = 9
        nums[index-1] = nums[index-1]-1

print(sum(nums))

Submission status: Accepted

Solution code:
N = int(input())
for i in range(18):
    a = (N + 1) // (10 ** i)
    if a:
        b = a
    elif a == 0:
        c = (i -1) * 9 + b - 1
        break
print(c)

Submission status: Accepted

Solution code:
n = input()
head = n[0]
tail = '0' * (len(n) - 1)
m = str(int(head + tail) - 1)
sumn = 0
summ = 0
for i in n:
    sumn += int(i)
for i in m:
    summ += int(i)
print(max(sumn, summ))

Submission status: Accepted

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

# -*- coding: utf-8 -*-
N = input()
Nint = int(N)
Nlist = list(map(int,list(N)))
l = len(N)
ans = 0
for i in range(l-1, 0, -1):
    Nint -= ((int(N[i]) + 1) % 10) * 10**(l-i-1)
    N = str(Nint)


ans = sum(list(map(int,list(N))))
print(ans)

Submission status: Accepted

Solution code:
def poyo():
    ans = -1
    A = []
    for i in range(1, 100):
        t = sum([ord(x) - ord('0') for x in str(i)])
        ans = max(ans, t)
        A.append(ans)
        # print(ans)

    import numpy as np
    maxi, cnt = np.unique(A, return_counts=True)
    print(maxi)
    print(np.cumsum(cnt))
    for x, y in zip(maxi, np.cumsum(cnt)):
        print(x, y)


def naive(N):
    ans = -1
    for i in range(N + 1):
        t = sum([ord(x) - ord('0') for x in str(i)])
        ans = max(ans, t)
    return ans


# poyo()
import math


def solve(N):
    if N < 10:
        return (N)
    else:
        ans = (len(str(N + 1)) - 1) * 9
        ans += ord(str(N + 1)[0]) - ord('0') - 1
        return (ans)


def check():
    for i in range(10000):
        # print(i)
        assert solve(i) == naive(i)


N = int(input())
print(solve(N))

Submission status: Accepted

Solution code:
n=input()
count=0

for i in range(len(n)):
    if n[i]=="9":
        count+=1

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

if len(n)==1:
    ans=int(n)


print(ans)

Submission status: Accepted

Solution code:
import sys
N1 = int(input())
temp = N1 -1
temp = list(map(int,list(str(temp))))
N2 = list(map(int,list(str(N1))))
# print(N2)
# print(temp)
if len(temp) != len(N2):
    print(sum(temp))
    sys.exit()
else:
    count = 0
    for i in range(1,len(N2)):
        if N2[i] == 9:
            count +=1
    if count == len(N2)-1:
        print(sum(N2)) 
        sys.exit()
    else:
        N2[0] = N2[0]-1
        for i in range(1,len(N2)):
            N2[i] = 9
        print(sum(N2))
        sys.exit()

Submission status: Accepted

Solution code:
import numpy as np
import scipy as sp
import scipy.sparse.csgraph as sg

N = [int(c) for c in input()]

for i in range(len(N)-1):
    if int(N[i]) + int(N[i+1]) < int(N[i]) - 1 + 9:
        N[i] -= 1
        for j in range(i+1, len(N)):
            N[j] = 9
num = sum(N)

print(num)

Submission status: Accepted

Solution code:
from sys import exit, stderr, setrecursionlimit
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect

def read():
  return int(input())

def reads():
  return [int(x) for x in input().split()]

setrecursionlimit(1000000)

N = [int(c) for c in input()]
L = len(N)

if all(N[i] == 9 for i in range(1, L)):
  print(sum(N))
else:
  print((N[0]-1) + 9 * (L-1))

Submission status: Accepted

Solution code:
# coding=utf-8
import re

n = input()
l = len(n)-1

def f(s):
    return sum(map(int, list(s)))

if l==0:
    print(n)
elif re.search("^9+$", n)!=None:
    print(9*(l+1))
else:
    r = max(f(n), 9*l + (int(n[0])-1))
    print(r)

Submission status: Accepted

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

import array
from bisect import *
from collections import *
import fractions
import heapq 
from itertools import *
import math
import random
import re
import string


def solve(N):
    N = str(N)
    ans = 0
    if N == len(N) * '9':
        ans = 9 * len(N)
    elif len(N) == 1:
        ans = int(N)
    elif N[1:] == (len(N)-1) * '9':
        ans = sum(map(int, list(N)))

    elif N[0] == '1':
        ans = 9 * (len(N) - 1)
    else:
        ans = int(N[0]) - 1 + 9 * (len(N)-1)
    return ans

N = input()
print(solve(N))

# assert(solve(100) == 18)
# assert(solve(9995) == 35)
# assert(solve(3141592653589793) == 137)
# assert(solve(1) == 1)
# assert(solve(9) == 9)
# assert(solve(10) == 9)
# assert(solve(18) == 9)
# assert(solve(19) == 10) # corner
# assert(solve(20) == 10)
# assert(solve(25) == 10)
# assert(solve(29) == 11)
# assert(solve(98) == 17)
# assert(solve(99) == 18)
# assert(solve(100) == 18)
# assert(solve(199) == 19)

# def straight(N):
#     N = int(N)
#     ans = 0
#     while N > 0:
#         ans = max(ans, sum(map(int, list(str(N)))))
#         N -= 1
#     return ans

# for i in range(1, 10000):
#     assert(straight(N) == solve(N))

Submission status: Accepted

Solution code:
n = int(input())
a = 0
while 10 ** a <= n:
    a = a + 1
b = (n + 1) // (10 ** (a -1))
c = b * (10 ** (a - 1)) - 1
d = 0
for i in range(len(str(c))):
    d = d + int(str(c)[i])
print(d)

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().rstrip()

#
ans = sum([int(x) for x in N])
for i in range(len(N)-1):
    A = str(int(N[:-(i+1)]) - 1)
    A += '9'*(i+1)
    #print(A)
    ans = max(ans, sum([int(x) for x in A]))
print(ans)

Submission status: Accepted

Solution code:
n = input()

def solve():
    import math
    for i in range(len(n)):
        if i>0:
            if n[i] != '9':
                print(int(n[0])-1+9*(len(n)-1))
                return
    print(int(n[0])+9*(len(n)-1))
    return

solve()

Submission status: Accepted

Solution code:
import sys

N = sys.stdin.readline().strip()

if len(N) == 1:
    print(N)
else:
    N2 = N[1:]
    if all(map(lambda d: d == '9', N2)):
        print(sum(map(int, N)))
    else:
        print(int(N[0]) - 1 + 9 * len(N2))

Submission status: Accepted

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

ans = sum(map(int, n))
ans = max(ans, max(map(lambda i: sum(map(int, list(str(int(''.join(n[:i + 1])) - 1)))) + (l - i - 1) * 9, range(l))))
print(ans)

Submission status: Accepted

Solution code:
from fractions import gcd
from math import factorial, ceil, sqrt, atan2, log, pi, e, asin,acos, cos, sin
from itertools import *
from fractions import Fraction
import string
import copy
import random
import bisect
from decimal import *
def id_generator(size=20, chars=string.digits):
    return ''.join(random.choice(chars) for _ in range(size))
 
def mp():
    return map(int,str(raw_input()).split())

n=input()
s=str(n)
ans=''
if s[0]!='9':
	print max(9*(len(s)-1)+(int(s[0])-1),sum(map(int,list(s))))
else:
	if s[1]=='0':
		print 9*(len(s)-1)+8
	else:
		i=0
		while i<len(s) and s[i]=='9':
			i+=1
		if i==len(s):
			print 9*len(s)
		else:
			if s[i]=='0':
				ans= 9*(len(s)-1)+8
			else:
				ans=9*(len(s)-1)+8
			print ans

Submission status: Accepted

Solution code:
n = int(input())
num = []
k = n
while k != 0 :
    num.append(k%10)
    k = k//10
print(max(sum(num), num[-1]-1+9*(len(num)-1)))

Submission status: Accepted

Solution code:
def main():
    N = input()

    if int(N) < 10:
        print(N)
        return

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

main()

Submission status: Accepted

Solution code:
a=input()

m=sum([int(i) for i in list(a)])
for i in range(1,len(a)):
  t=str(int(a[:i])-1)
  h=a[i:]
  m=max(sum([int(i) for i in list(t)])+9*len(h),m)

print(m)

Submission status: Accepted

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

    res = sum(N)

    for i in range(len(N)):
        tmp = 0
        for j in range(len(N)):
            if j <= i-1:
                tmp += N[j]
            elif j==i:
                tmp += N[j]-1
            else:
                tmp += 9
        res = max(res, tmp)

    print(res)


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
N = input()
n = []
for i in N:
    n.append(int(i))
for i in range(len(n)):
    if i == len(n)-1:
        break
    if n[-(i+1)] != 9:
        n[-(i+1)] = 9
        n[-(i+2)] -= 1
print(sum(n))

Submission status: Accepted

Solution code:
s = input()
s_n = int(s)
dig = len(s)

if dig == 1:
	cnt = 0
	for i in range(len(s)):
		cnt += int(s[i])
	print(cnt)
	exit(0)

flg = 1
for i in range(1,len(s)):
	if s[i] != '9':
		flg = 0
		break

if flg == 1:
	cnt = 0
	for i in range(len(s)):
		cnt += int(s[i])
	print(cnt)
	exit(0)

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

Submission status: Accepted

Solution code:

def score(s):
    return sum(map(int, s))


def main():
    s = input()
    best = score(s)
    for i in range(1, len(s)):
        ss = int(s) // 10**i * 10**i - 1
        best = max(best, score(str(ss)))
    print(best)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

c = str(N)[0]

if c == 1:
    B = 9 * (len(str(N))-1)
else:
    B = int(c) + 9 * (len(str(N)) - 1) - 1


print(max(A, B))

Submission status: Accepted

Solution code:
S = input()
L = len(S)
N = int(S)
ans = sum([int(c) for c in S])
for i in range(1,L):
    tmp = sum([int(c) for c in S[:i]]) - 1
    tmp += 9*(L-i)
    ans = max(ans, tmp)
print(ans)

Submission status: Accepted

Solution code:
n = input()
total = 0
first = 0
for i in range(len(n)):
	first += int(n[i])
if len(n) == 1:
	print(n)
else:
	for i in range(len(n)):
		if i == 0:
			total += int(n[i]) -1
		else:
			total += 9
	if first < total:
		print(total)
	else:
		print(first)

Submission status: Accepted

Solution code:
N = input()

def total(n):    
    t = 0
    for i in n:
        t += int(i)
    return t

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

Submission status: Accepted

Solution code:
n = input()
n2 = [int(i) for i in n[::-1]]
ans = [sum(n2)]
for i in range(len(n2)-1):
    n2[i] = 9
    n2[i+1] -= 1
    ans.append(sum(n2))
ans.append(sum(n2))
print(max(ans))

Submission status: Accepted

Solution code:
def main():
    N = [int(c) for c in input()]
    for i in range(len(N)):
        s = sum(N)
        ns = N[i]-1 + (len(N) - i - 1) * 9
        if s < ns:
            print(ns)
            return
    print(s)

main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def sumOfDigits(a):
    sm = 0
    while(a!=0):
        sm = sm + a % 10
        a = a // 10
     
    return sm
     
# Returns the maximum number
# with maximum sum of digits.
def findMax(x) :
     
    # initializing b as 1
    # and initial max sum
    # to be of n
    b = 1
    ans = x
     
    # iterates from right
    # to left in a digit
    while (x!=0) :
        # while iterating this 
        # is the number from
        # right to left
        cur = (x - 1) * b + (b - 1)
         
        # calls the function to
        # check if sum of cur is
        # more then of ans
        if (sumOfDigits(cur) > sumOfDigits(ans) or
        (sumOfDigits(cur) == sumOfDigits(ans) and
            cur > ans)) :
                ans = cur
 
        # reduces the number
        # to one unit less
        x =x // 10
        b = b * 10
     
     
    return ans

def sum_digits(n):
    s = 0
    while n:
        s += n% 10
        n //= 10
    return s
# driver program to test the above function
n = int(input())
maxDigit = findMax(n)
print(sum_digits(maxDigit))

Submission status: Accepted

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


def digit_sum(n):
    return sum(int(c) for c in str(n))


def find_max(x):
    a = x
    b = 1
    while x:
        c = (x - 1) * b + (b - 1)
        dsc = digit_sum(c)
        dsa = digit_sum(a)
        if dsc > dsa or dsc == dsa and c > a:
            a = c
        x //= 10
        b *= 10
    return digit_sum(a)


def main():
    print(find_max(int(input())))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def calc(x):
    r = 0
    while x:
        r += x % 10
        x = x // 10
    return r

def solve0(N):
    r = max(calc(i) for i in range(N + 1))
    return r

def solve(N):
    if N < 10:
        return N
    x = N % 10
    if x == 9:
        return solve(N // 10) + x
    else:
        return solve(N // 10 - 1) + 9

N = int(input())

print(solve(N))

Submission status: Accepted

Solution code:
N=raw_input()
if len(N)<=1:
  print N
elif N[1:]=="9"*(len(N)-1):
  print sum(map(int, N))
else:
  print int(N[0])-1+9*(len(N)-1)

Submission status: Accepted

Solution code:
n = input()

#print(n)
#print(n[0])
#n
maxt1=0
for i in range(len(n)):
    maxt1+= int(n[i])

#999
maxt2=(len(n)-1)*9+int(n[0])-1

print(max(maxt1,maxt2))

Submission status: Accepted

Solution code:
s = map(int, raw_input().strip())
ans = sum(s)
t = 0
for i, x in enumerate(s):
    if x > 0:
        tt = t + x - 1 + 9 * (len(s) - i - 1)
        if ans < tt:
            ans = tt
        t += x
print ans

Submission status: Accepted

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

for i in reversed(range(len(lis))):
    if i - 1 == -1:
        break
    if lis[i] < 9:
        lis[i-1] -= 1
        lis[i] = 9

print(sum(lis))

Submission status: Accepted

Solution code:
N = input()


def digitsum(n):
    s = str(n)
    S = 0
    for i in s:
        S += int(i)
    return S


d = len(str(N)) - 1
k = int(N[0])
print(max([digitsum(N),digitsum((k*10**d)-1)]))

Submission status: Accepted

Solution code:
N = input()
flag = True
for i in range(1, len(N)):
    if N[i] != '9':
        flag = False
        break

if flag:
    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()
ans = sum(list(map(int, list(n))))
for i in range(len(n)):
    cow = sum(list(map(int, str(int(n[:i+1]) - 1) + str((len(n) - i - 1) * "9"))))
    ans = max(cow, ans)
print(ans)

Submission status: Accepted

Solution code:
N=input()
cnt=0
for i in range(len(N)):
  cnt+=int(N[i])

a=int(N[0])
a+=(len(N)-1)*9-1
a=max(a,cnt)

print(a)

Submission status: Accepted

Solution code:
import sys

s=list(input())
ret=0
while True:
    tmp=0
    for i in s:
        tmp+=int(i)
    ret=max(ret,tmp)
    for i in reversed(range(len(s))):
        if s[i]!="9":
            if i==0:
                print(ret)
                sys.exit()
            else:
                j=i-1
                while s[j]=="0":
                    j-=1
                s[j]=str(int(s[j])-1)
                j+=1
                while j<len(s):
                    s[j]="9"
                    j+=1
                break
    else:
        print(ret)
        break

Submission status: Accepted

Solution code:
#!/usr/bin/env python
N = int(input())
if N < 9:
    print(N)
    exit(0)
n = 0
while True:
    nxt = n * 10 + 9
    if nxt > N:
        break
    n = nxt

ans = n
for i in range(1, 10):
    n1 = int(str(i) + str(n))
    if n1 <= N:
        ans = n1
s = 0
while(ans):
    s += ans % 10
    ans = ans // 10
print(s)

Submission status: Accepted

Solution code:
a = input()

res = 0
tmp = 0

while True:
    res = max(res, sum(map(int, str(a))) + tmp)
    a /= 10
    if a == 0:break
    a-=1
    tmp += 9

print res

Submission status: Accepted

Solution code:
INF = 999999999999999999L
EPS = 1e-12

def read():
    return raw_input().strip()

def read_ints():
    return map(int,read().split())

def get_digits(N):
    digs = []
    while N > 0:
        digs.append(N%10)
        N /= 10 
    digs.reverse()
    return digs
        
N = int(read())
digits = get_digits(N)
a1 = sum(digits)
digits = [digits[0]-1] + [9]*(len(digits)-1)
#print digits
a2 = sum(digits)
print max(a1,a2)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input())
ret = 0
i = True
while (n>=9):
    ret += 9
    i = i and (n%10==9)
    n //=10
ret += n-1
if i: ret += 1
print(ret)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n = I()
    s = str(n)
    a = [int(c) for c in s]
    r = sum(a)
    for i in range(len(a)):
        t = sum(a[:i+1]) - 1
        t += (len(a) - i - 1) * 9
        if r < t:
            r = t


    return r


print(main())

Submission status: Accepted

Solution code:
n = input()
def F(n):
	return sum(map(int, list(str(n))))

t = 1
z = F(n)
while n > 0:
	n -= n % t
	if n == 0:
		break
	z = max(z, F(n))
	z = max(z, F(n - 1))
	t *= 10
print z

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
N = input()
l = list(map(int,N))
i = 0
#ans = l[0] - 1 + (len(l)-1)*9 #暫定の答え

if int(N) < 9:
    ans  = 0
elif l.count(9) >= len(l)-1:
    if l[len(l)-1] != 9:
        spot = 8
    else:
        spot = min(l)

else:
    while True:
        if l[i] < 9 and i < len(l)-1:
            spot = l[i] - 1
            break
        else:
            i += 1 
ans = spot + (len(l)-1)*9
print(ans)

Submission status: Runtime Error

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

Submission status: Runtime Error

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

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
def examA():
    N = SI()
    n = len(N)
    ans = (n-1)*9 + int(N[0]) - 1
    if int(N[1:])==int("9"*(n-1)):
        ans += 1
    print(ans)
    return

# 参考 https://atcoder.jp/contests/agc021/submissions/8392122
def examB():
    def norm2(vec):
        return math.sqrt(vec[0] ** 2 + vec[1] ** 2)
    # any 2 points must have different position.
    def ConvexHull(point_list):
        pos2idx = {point_list[i]: i for i in range(len(point_list))}
        y_val = defaultdict(list)
        x_list = sorted(list(set([p[0] for p in point_list])))
        for x, y in point_list:
            y_val[x].append(y)

        upper = [(x_list[0], max(y_val[x_list[0]]))]
        lower = [(x_list[0], min(y_val[x_list[0]]))]
        prev = float('inf')
        for xi in x_list[1:]:
            x0, y0 = upper[-1]
            x1, y1 = xi, max(y_val[xi])
            if (y1 - y0) / (x1 - x0) < prev:
                upper.append((x1, y1))
                prev = (y1 - y0) / (x1 - x0)
            else:
                while True:
                    x0, y0 = upper[-1]
                    if len(upper) == 1:
                        upper.append((x1, y1))
                        break
                    x00, y00 = upper[-2]
                    if (y1 - y0) / (x1 - x0) > (y1 - y00) / (x1 - x00):
                        upper.pop()
                    else:
                        prev = (y1 - y0) / (x1 - x0)
                        upper.append((x1, y1))
                        break

        prev = -float('inf')
        for xi in x_list[1:]:
            x0, y0 = lower[-1]
            x1, y1 = xi, min(y_val[xi])
            if (y1 - y0) / (x1 - x0) > prev:
                lower.append((x1, y1))
                prev = (y1 - y0) / (x1 - x0)
            else:
                while True:
                    x0, y0 = lower[-1]
                    if len(lower) == 1:
                        lower.append((x1, y1))
                        break
                    x00, y00 = lower[-2]
                    if (y1 - y0) / (x1 - x0) < (y1 - y00) / (x1 - x00):
                        lower.pop()
                    else:
                        prev = (y1 - y0) / (x1 - x0)
                        lower.append((x1, y1))
                        break

        # return upper, lower
        # return [pos2idx[xy] for xy in upper], [pos2idx[xy] for xy in lower]

        upper_idx, lower_idx = [pos2idx[xy] for xy in upper], [pos2idx[xy] for xy in lower]
        if upper_idx[-1] == lower_idx[-1]:
            upper_idx.pop()
        CH_idx = upper_idx
        CH_idx.extend(reversed(lower_idx))
        if CH_idx[0] == CH_idx[-1] and len(CH_idx) > 1:
            CH_idx.pop()
        return CH_idx

    N = I()
    P = [[]for _ in range(N)]
    D = defaultdict(int)
    for i in range(N):
        x,y = LI()
        P[i] = (x,y)
        D[(x,y)] = i
    C = ConvexHull(P)
    ans = [0]*N
    if len(C)==2:
        for c in C:
            ans[c] = 0.5
        for v in ans:
            print(v)
        return
    #print(C)
    for i,c in enumerate(C):
        s, t, u = C[i - 1], C[i], C[(i + 1) % len(C)]
        x0, y0 = P[s]
        x1, y1 = P[t]
        x2, y2 = P[u]
        vec0 = (y0 - y1, x1 - x0)
        vec1 = (y1 - y2, x2 - x1)
        ans[t] =  math.acos((vec0[0] * vec1[0] + vec0[1] * vec1[1]) / (norm2(vec0) * norm2(vec1))) / (2 * math.pi)
    for v in ans:
        print(v)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    S = SI()
    N = len(S)
    K = I()
    if K>150:
        K = 150
    dp = [[[0]*(K+1) for _ in range(N)] for i in range(N)]
    for i in range(N):
        for j in range(K+1):
            dp[i][i][j] = 1
    for i in range(2,N+1):
        for k in range(K+1):
            for l,r in enumerate(range(i-1,N)):
                if S[l]==S[r]:
                    dp[l][r][k] = dp[l+1][r-1][k] + 2
                else:
                    if k>0:
                        dp[l][r][k] = max(dp[l+1][r][k],dp[l][r-1][k],dp[l+1][r-1][k-1]+2)
                    else:
                        dp[l][r][k] = max(dp[l + 1][r][k], dp[l][r - 1][k])
    ans = max(dp[0][-1])
    #print(dp)
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

from decimal import Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examA()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Submission status: Runtime Error

Solution code:
import math
n = int(input())
ln = int(math.log10(n))
#1つ下の桁がない場合
if ln == 0:
  print(n)
#全ての桁が9の場合
elif (n+1) % (10 ** (ln + 1)) == 0:
  print(9 * (ln + 1))
#それ以外
else:
  a = n // (10 ** ln)
  b = a * (10 ** ln )- 1
  c = [int(x) for x in list(str(b))]

  print(sum(c))

Submission status: Runtime Error

Solution code:
import math
n = int(input())
ln = int(math.log10(n))
if ln == 0:
  print(n)
else:
  a = n // (10 ** ln)
  b = a * (10 ** ln )- 1
  c = [int(x) for x in list(str(b))]

  print(sum(c))

Submission status: Runtime Error

Solution code:
import math
n = int(input())
ln = int(math.log10(n))
a = n // (10 ** ln)
b = a * 10 ** ln - 1
c = [int(x) for x in list(str(b))]

print(sum(c))

Submission status: Runtime Error

Solution code:
def i():
	return int(input())
def i2():
	return map(int,input().split())
def s():
	return str(input())
def l():
	return list(input())
def intl():
	return list(int(k) for k in input().split())

n = i()

a = len(str(n))
ans = 0
memo = 0
for i in range(10**(a-2), n+1 ):
	for j in range( len(str(i)) ):
		i = str(i)
		memo += int(i[j])
	ans = max( memo, ans )
	memo = 0
print(ans)

Submission status: Runtime Error

Solution code:
#AtCoder Grand Contest 021 a
def wa(x):
    x=str(x)
    s=0
    for i in x:
        s+=int(i)
    return s

n=int(input())
keta=len(str(n))
start=10**(keta-2)
start=max(0,start)
ans=0
print(start)
for i in range(start,n+1):
    ans=max(ans,wa(i))
print(ans)

Submission status: Runtime Error

Solution code:
n=input()

l=len(n)
if int(n)>9:
  ans=[9]
else:
  print(int(n))
  exit()
tmp=n[l-1]
for i in range(2,l+1):
  #print(tmp, int(n[l-i]))
  if int(tmp) != 9:
    tmp=int(n[l-i])-1
    #print("tmp:",tmp)
  if i==l:
    ans.append(tmp)
  else:
    ans.append(9)
  #print(ans)
print(sum(ans))