Problem:


Score : 300 points

Problem Statement

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

Constraints

1\leq N \leq 10^{16}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

100

Sample Output 1

18

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

Sample Input 2

9995

Sample Output 2

35

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

Sample Input 3

3141592653589793

Sample Output 3

137



Sample input:
100


Sample output:
18

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

num = int(raw_input())
length = len(str(num))
sum_of_num = sum(list(map(int,list(str(num)))))
max_of_num = int(str(num)[0])-1+(length-1)*9
print max(sum_of_num,max_of_num)

Submission status: Accepted

Solution code:
N = list(input())
lenN = len(N)
retN = []
toNext = 0
for n in reversed(N):
    n = int(n) + toNext
    lenN = lenN - 1
    toNext = 0
    if n < 9 and lenN != 0:
        toNext = -1
        retN.append(9)
        continue
    retN.append(n) 

print(sum(retN))

Submission status: Accepted

Solution code:
N=input()
num=0
if int(N)<10:
    print(N)
else:
    for i in range(len(N)-2):
        num+=9
    x=max(int(N[0])+int(N[len(N)-1]),(int(N[0])-1)+9)
    print(num+x)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
low = '9'*(len(str(n))-1)
pos=''
for i in range(1, 10):
    if int(str(i)+low)<=n:
        pos=str(i)
if pos=='':
    pos='0'
print(len(low)*9 + int(pos))

Submission status: Accepted

Solution code:
N = list(str(input()))
mx = sum(map(lambda x: ord(x)-ord('0'),N))
for i in xrange(1,len(N)):
    N[i]='0'
N = int("".join(N))
mx = max(mx,sum(map(lambda x: ord(x)-ord('0'),str(N-1))))
print mx

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
n = int(raw_input())

def digit_sum(num):
    ret = 0
    while num > 0:
        ret = ret + num % 10
        num = num // 10
    return ret

ans = digit_sum(n)
buff = n
d = 10
while n > 0:
    n = n // 10
    buff = (buff // d) * d - 1
    d = d * 10
    if buff < 0 : break
    ans = max([ans,digit_sum(buff)])

print ans

Submission status: Accepted

Solution code:
s = input()

res = 0

i = True
p = 1
for c in s:
    if p == 1:
        p = 0
    elif c != '9':
        i = False
        break

if len(s) == 1:
    res = int(s)
elif i:
    res += int(s[0])
else:
    res += int(s[0]) - 1

res += (len(s) - 1) * 9
print(res)

Submission status: Accepted

Solution code:
n = input().rstrip()
if len(n) == 1:
  print(n)
else:
  flg = True
  for i in range(1,len(n)):
    if n[i] != '9':
      flg = False
  if flg:
    print(9*(len(n)-1)+int(n[0]))
  else:
    print(9*(len(n)-1)+int(n[0])-1)

Submission status: Accepted

Solution code:
import sys

a = int(input())
start = 0
power = 1
ans = 0
while True:
    for i in range(9):
        ans += 1
        start += power
        if start-1 >= a:
            print(ans-1)
            sys.exit()
    power *= 10

Submission status: Accepted

Solution code:
n=int(input())
if n<10:
  print(n)
else:
  L=list(map(int, list(str(n))))
  if(L.count(9)==len(L)) or (L[0]!=9 and L.count(9)==len(L) -1):
    print(sum(L))
  else :
    print(9*(len(L)-1)+int(L[0])-1)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

if all([N[i] == "9" for i in range(1, le)]):
    ans = sum([int(N[i]) for i in range(le)])
else:
    tmp = int(N[0]) * (10 ** (le - 1)) - 1
    ans = sum([int(t) for t in str(tmp)])
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
  problem:
    https://agc021.contest.atcoder.jp/tasks/agc021_a
"""

from __future__ import print_function
import sys

def solve(_input):
    """
    main function.

    Arguments:
    _input -- string of the format "n p", where n and p are positive integer, separated by space " ".
    """

    # input validation
    _li = list(_input.strip())
    try:
        _digits = map(int,_li)
    except (ValueError, IndexError) as ex:
        print ('[ERROR] Please input a whole number', ex)
        return -1

    # preprocessing
    _ans = sum(_digits)

    for _i in range(0,len(_digits)-1):

        if ( _digits[_i] == 0 ):
            continue

        _r = 0
        
        for _j in range(0,_i - 1):
            _r += _digits[_j]
        
        _r += _digits[_i] - 1

        _r += (len(_digits) - _i - 1) * 9

        _ans = max(_ans, _r)

    return _ans

# call
print (solve(sys.stdin.readline()))

Submission status: Accepted

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

ans = sum(map(int, N))
num = 0
for i in range(L):
    d = N[i]
    if d == '0':
        continue
    num += int(d)
    ans = max(num - 1 + 9*(L-i-1), ans)
print(ans)

Submission status: Accepted

Solution code:
import math

N = int(input())
digit_num = math.ceil(math.log10(N))
msd =int(N/(10**(digit_num-1)))

if (N+1)%10 == 0:
    print(msd + 9*(digit_num-1))
elif N-10<0:
    print(N)
else:
    print(msd + 9*(digit_num-1) - 1)

Submission status: Accepted

Solution code:
import math

n = int(input())
digit = len(str(n))
digit -= 1

m = n - math.pow(10, digit) + 1
print(int(digit * 9 + (m // math.pow(10, digit))))

Submission status: Accepted

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

for i in range(1, K):
    if N[i] != '9':
        c -= 1
        break

ret = c + 9 * (K - 1)

print(ret)

Submission status: Accepted

Solution code:
N = input()
if len(N) == 1:
    print(int(N))
    exit()

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

Submission status: Accepted

Solution code:
#agc021a

n=int(raw_input())
res=0
n+=1
while n>9:
 res+=9
 n/=10
print res+n-1

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding: utf-8
s=list(map(int,list(input())))
mx=sum(s)
for i in range(len(s)):
    mx=max(sum(s[0:i+1])-1+9*(len(s)-i-1),mx)
print(mx)

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    N = input()
    if len(N) == 1:
        print(N)
    else:
        cand_1 = sum([int(_) for _ in N])
        cand_2 = 9 * (len(N) - 1) + int(N[0]) - 1

        if cand_1 > cand_2:
            print(cand_1)
        else:
            print(cand_2)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
n = input()
d = len(n)

res = 0
if d >= 2:
    res = 9*(d-1) + int(n[0]) - 1

res = max(res,sum(map(int,n)))
# print(n[0])
# print(sum(map(int,n)))
print(res)

Submission status: Accepted

Solution code:
N = input()

num_list = [sum(map(int, N))]
l = len(N)
head = 0

for i, num in enumerate(N):
    if num == 0:
        continue
    num_list += [head + int(num) - 1 + 9 * (l - i - 1)]
    head += int(num)

print(max(num_list))

Submission status: Accepted

Solution code:
a = input()
b = str()
l = len(a) 
for i in range(1, l):
    b += (a[i])
p = str(9) * (l-1)
if b == p:
    ans = 9 * (l-1) + int(a[0])
else:
    ans = 9 * (l-1) + int(a[0]) - 1
print(ans)

Submission status: Accepted

Solution code:
n = input()

a = n[0]

if len(n) > 1:
    b = n[1:]
    if (int(b)+1) % (10 ** len(b)) == 0:
        flag = True
    else:
        flag = False
else:
    b = ''
    flag = True

if flag:
    ans = int(a) + 9 * len(b)
else:
    ans = int(a) - 1 + 9 * len(b)

print(ans)

Submission status: Accepted

Solution code:
s=input();n=len(s);a=0;b=0
for i in range(n):
    a+=int(s[i])
for i in range(n):
    if i!=0:
        b+=9
    else:
        b+=(int(s[0])-1)
print(max(a,b))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
print(sum([int(j) for j in str(int(str(n+1)[0])-1) + "9"*(len(str(n+1))-1)]))

Submission status: Accepted

Solution code:
n = int(input())

def digit_sum_simple(n):
    
    max_sum = -1

    for i in range(10**(len(str(n))-1)-1, n+1):
        
        i_parts = []
        for i_part in str(i):
            i_parts.append(int(i_part))

        this_sum = sum(i_parts)
        
        if max_sum < this_sum:
            max_sum = this_sum
            max_sum_i = i

    return max_sum, max_sum_i

def digit_sum_temp(n):
    max_sum_i = int(str(int(str(n+1)[0])-1) + "9"*(len(str(n+1))-1))
    max_sum = sum([int(j) for j in str(max_sum_i)])

    return max_sum

print(digit_sum_temp(n))

Submission status: Accepted

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

def d(i):
    if i > len(n) - 1: return
    d(i+1)
    v2 = n[i] - 1 if n[i] != 0 else 9
    l.append(v2 + (ln - i) * 9)

d(0)
print(max(l))

Submission status: Accepted

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

Submission status: Accepted

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

max = 0
max2 = 0
if n < 10:
    print(n)
else:
    while m > 0:
        max += int(m % 10)
        m = m/10
    m=n
    while True:
        if m >= 10:
            max2 += int(9)
        else:
            max2 += int(m % 10 - 1)
            break
        m = m / 10
    if max > max2:
        print(max)
    else:
        print(max2)

Submission status: Accepted

Solution code:
n = int(input())
 
for i in range(10)[::-1]:
	if n >= int(str(i) + '9'*(len(str(n))-1)):
		print(i + 9*(len(str(n))-1))
		break

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
def inpl(): return list(map(int, input().split()))
N = input()

res = 0
for i, j in enumerate(N):
    if j != "9":
        break

if i >= 2:
    res += 9*(i-1)
    N = N[i-1:]

A = 10**(len(N)-1)

res += max(sum(map(int, N)), sum(map(int, str(int(N)//A*A-1))))
print(res)

Submission status: Accepted

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

# AtCoder Grand Contest
# Problem A


def get_most_significant_digit(number: int):
    separated_number = list(map(int, str(number)))
    return separated_number[0]


def count_digit(number: int):
    return len(str(number))


def generate_candidate_value(most_significant_digit, digit_count):
    filled_with_9 = 10 ** (digit_count - 1) - 1

    if digit_count > 1:
        candidate_value = str(most_significant_digit) + str(filled_with_9)
    else:
        candidate_value = str(most_significant_digit)
    return int(candidate_value)


def sum_digit(number: int, candidate_value: int):
    result = sum(list(map(int, str(candidate_value))))

    if number >= candidate_value:
        return result
    else:
        return result - 1


if __name__ == '__main__':
    number = int(input())

    # See: https://img.atcoder.jp/agc021/editorial.pdf
    most_significant_digit = get_most_significant_digit(number)
    digit_count = count_digit(number)
    candidate_value = generate_candidate_value(most_significant_digit,
                                               digit_count)

    result = sum_digit(number, candidate_value)
    print(result)

Submission status: Accepted

Solution code:
n = int(input())

for i in range(10)[::-1]:
	if n >= int(str(i) + '9'*(len(str(n))-1)):
		print(i + 9*(len(str(n))-1))
		break

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    # n = 100
    # n = 9995
    # n = 3141592653589793
    n = input()

    ary = list(map(int, list(str(n))))

    # x..xxの全探索
    m = -1
    middle = [9 for i in range(0, len(ary[1:-2]))] # 数列の真ん中
    for i in range(0, 10):
        for j in range(0, 10):
            for k in range(0, 10):
                if m < sum([i] + middle + [j, k]) and int(''.join(map(str, [i] + middle + [j, k]))) <= int(n):
                    m = sum([i] + middle + [j, k])
    print(m)

Submission status: Accepted

Solution code:
import sys

if __name__ == '__main__':
    # n = 100
    # n = 9995
    # n = 3141592653589793
    n = input()

    ary = list(map(int, list(str(n))))

    # ひと桁のときの対応
    if len(ary) == 1:
       print(sum(ary))
       sys.exit()

    # ふた桁のときの対応
    if len(ary) == 2:
        if sum(ary) <= 9:
            print(9)
            sys.exit()
        else:
            print(sum(ary))
            sys.exit()

    # すでに9が並んでたら上位を減らさない
    if ary[1:-1].count(9) != len(ary[1:-1]):
        ary[0] = ary[0] - 1
        ary[-2] = 9
        ary[-1] = 9

    # 真ん中はすべて9にする
    ary[1:-1] = [9 for i in range(0, len(ary[1:-1]))]

    # 下位が99 or 98でなかったら下位を89にする
    if sum(ary[-2:]) < 18:
        ary[-2] = 8
        ary[-1] = 9

    # print(ary)
    print(sum(ary))

Submission status: Accepted

Solution code:
s=input()
a=int(s[0])
b=sum([int(s[i]) for i in range(len(s))])
for i in range(1,len(s)):
 if s[i]!="9":
    b=a+9*(len(s)-1)-1
    break

print(b)

Submission status: Accepted

Solution code:
import math
n=int(input())
s = str(n)
array = list(map(int, list(s)))
a1=sum(array)
size = int (math.log10(n))
a2=int(n/(10**size))-1+size*9
print(max(a1,a2))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
if N < 10 :
  print(N)
else :
  L = list(map(int, list(str(N))))
  if (L.count(9) == len(L)) or (L[0] != 9 and L.count(9) == len(L) -1) :
    print(sum(L))
  else :
    print(9 * (len(L) - 1) + int(L[0]) - 1)

Submission status: Accepted

Solution code:
if __name__=='__main__':
    N = int(input())

    N_list = list(map(int, list(str(N))))
    if len(N_list) == 1:
        print(N_list[0])
    elif set(N_list[1:]) == {9}:
        print(sum(N_list))
    else:
        N_list[0] -= 1
        for i in range(1, len(N_list)):
            N_list[i] = 9
        print(sum(N_list))

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

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

    # 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:
#encoding=utf-8
def solve(n):
    ans_a = calc_digit_sum(n)
    ans_b = calc_digit_sum(n - n % 10 - 1)
    ans_c = calc_digit_sum(10 ** (len(str(n)) - 1) - 1 + 10 ** (len(str(n)) - 1) * (int(str(n)[0]) - 1) )
    return max(ans_a, ans_b, ans_c)

def calc_digit_sum(n):
    if n <= 0:
        return 0
    str_n = str(n)
    ans = 0
    for x in range(len(str_n)):
        ans = ans + int(str_n[x])
    return ans

if __name__ == "__main__":
    n = int(input())
    print(solve(n))

Submission status: Accepted

Solution code:
def digit_num(_num):
    _digit = 0
    while _num:
        _digit += 1
        _num //= 10
    return _digit

def ACGC021_A():
    _num = int(input())
    _digit = digit_num(_num)
    _topdig = _num // 10 ** (_digit - 1)
    if (_num - _topdig * 10 ** (_digit - 1)) == 10 ** (_digit - 1) - 1:
        print(_topdig + 9 * (_digit - 1))
    else:
        print(_topdig - 1 + 9 * (_digit - 1))

ACGC021_A()

Submission status: Accepted

Solution code:
N_list = [int (i) for i in list(input())]
digit = 0
dflag = False
max = 0
for i in N_list:
    max += i

for i in N_list:
    if i == 9:
        dflag = True
    else:
        break

    digit += 1

if dflag:
    N_list[digit-1] -=1
    for i in range(digit, len(N_list)):
        N_list[i] = 9

else:
    N_list[digit] -=1
    for i in range(digit+1, len(N_list)):
        N_list[i] = 9

sum = 0

for i in N_list:
    sum += i

if sum > max:
    max = sum
print (max)

Submission status: Accepted

Solution code:
def digit_num(_num):
    _digit = 0
    while _num:
        _digit += 1
        _num //= 10
    return _digit


_num = int(input())
_digit = digit_num(_num)
_topdig = _num // 10 ** (_digit - 1)
_sumlist = [9 * (_digit - 1)]
if (_num - _topdig * 10 ** (_digit - 1)) == 10 ** (_digit - 1) - 1:
    _sumlist.append(_topdig + 9 * (_digit - 1))
else:
    _sumlist.append(_topdig - 1 + 9 * (_digit - 1))

print(max(_sumlist))

Submission status: Accepted

Solution code:
n = input()
list = [10**i for i in range(1,20)]

if int(n)>=10:
    ans = 9*(len(n)-1)+int(n[0])-1
    if (int(n[1:])+1) in list: ans+=1
else: ans = int(n)

print(ans)

Submission status: Accepted

Solution code:
import sys

n = int(input())
s = len(str(n))

_max = ""
for i in range(1, s+1):
    _max += "9"
if str(n).count("9") == s:
    print(s*9)
else:
    for j in range(1, 10):
        for k in range(0, s):
            if int(_max) - j*10**k <= n:
                tmp = str(int(_max) - j*10**k)
                amari = tmp.replace("9", "")
                if len(amari) != 0:
                    print(tmp.count("9")*9+int(amari))
                else:
                    print(tmp.count("9")*9)
                sys.exit()

Submission status: Accepted

Solution code:
N = input()

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

Submission status: Accepted

Solution code:
def is_9(arr):
    s = []
    for i in range(len(arr)):
        if arr[i] != '9':
            return False
        s.append(arr[i])
    return True


n = list(input())
fd = int(n.pop(0))
if is_9(n):
    print(fd + int(9 * len(n)))
else:
    print(fd - 1 + int(9 * len(n)))

Submission status: Accepted

Solution code:
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

INF = float('inf')
MOD = 1000000000 + 7

def LI(): return [int(x) for x in input().split(" ")]
def LS(): return [str(x) for x in input().split(" ")]
def ItoS(L): return [str(x) for x in L]
def StoI(L): return [int(c) for c in L]

def check(n):
    l = len(str(n))
    for ele in list(str(n)):
        if ele != "9":
            return False

    return True

def Sum(n):
    L = list(str(n))
    sum = 0
    for ele in L:
        sum += int(ele)

    return sum

def solve():
    while 1:
        try:
            n = int(input())
            if 1 <= n <= 9:
                print(n)
                raise EndLoop

            l = len(str(n))

            tmp = str(n)[0]

            if check(n):
                print(9 * l)
            else:
                print(max(Sum(n), 9 * (l - 1) + int(tmp) - 1))
            break
        except:
            break

solve()

Submission status: Accepted

Solution code:
N = int(input())
num = str(N)
for i in range(1,len(num)):
    if num[-i] != "9" and 0 < N - (int(num[-i]) + 1) * 10**(i-1):
        N -= (int(num[-i]) + 1) * 10**(i-1)
        num = str(N)

D = 0
for digit in str(N):
    D += int(digit)

print(D)

Submission status: Accepted

Solution code:
N = int(input())
def calc(N):
    if len(str(N)) == 1:
        return N
    if len(list(set(str(N)[1:]))) == 1 and '9' in  list(set(str(N)[1:])):
        return int(str(N)[0])+9*len(str(N)[1:])
    ret = 0
    f = 0
    for idx,c in enumerate(str(N)):
        tmp = int(c)
        if f == 1:
            ret += 9
            continue
        if tmp != 9 and idx == 0:
            ret += tmp-1
            f = 1
            continue
        elif tmp != 9:
            ret -= 1
            f = 1
            ret += 9
            continue
        else:
            ret += 9
            continue
    return ret
print(calc(N))

Submission status: Accepted

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

if N <= 9:
	print(N)
	exit(0)

ans=0
b = False
for i in range( len(S) ):
	if i==0:
		ans += int(S[i])
		continue
	
	j = int(S[i])
	#print(i, j, ans)
	
	if b:
		ans += 9
	else:
		if j==9:
			ans += j
		if j!=9:
			b = True
			ans -= 1
			ans += 9

print(ans)

Submission status: Accepted

Solution code:
def A_Digit_Sum_2():
    a=input()
    count=0
    c=0
    for i in range(len(a)-1):
        if a[i+1]=='9':
            count+=1
    #print(count)
    if count==(len(a)-1):
        for i in range(len(a)):
            c+=int(a[i])
    else:
        c=(len(a)-1)*9+int(a[0])-1
    print(c)

A_Digit_Sum_2()

Submission status: Accepted

Solution code:
N=int(input())
num_digits=0
for i in range(17):
    if N//(10**i)>0: num_digits=i
max_digits=N//(10**num_digits)
nines=9
if num_digits==0: print(max_digits)
else:
    for i in range(1,num_digits):
        nines+=9*10**i
    temp=N-max_digits*10**num_digits
    if temp/nines==1: print(max_digits+num_digits*9)
    else: print((max_digits-1)+num_digits*9)

Submission status: Accepted

Solution code:
N = list(input())
if len(N) == 1:
    print(int(N[0]))
elif N.count('9') == len(N):
    print(len(N) * 9)
else:
    for i in range(len(N)):
        if N[i] != '9':
            idx = i
            break
    if idx == len(N) - 1:
        print(sum(map(int, N[:-1])) + 8)
    else:
        if N[idx] == '0':
            print(len(N) * 9 - 1)
        elif N[idx + 1:].count("9") == len(N[idx + 1:]):
            print(sum(map(int, N)))
        else:
            print(sum(map(int, N[:idx + 1])) + (len(N) - idx - 1) * 9 - 1)

Submission status: Accepted

Solution code:
from collections import Counter
n = input()
c = Counter(n)
n9 = c['9']
if n9 == len(n):
    ans = 9*len(n)
elif n9 == len(n)-1 and n[0] != '9':
    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:
import sys

if __name__ == "__main__":
    N = int(input())
    digit = len(str(N))
    digit_list = [int(x) for x in list(str(N))]
    if digit == 1:
        print(N)
        sys.exit()
    buf = 0
    for i in range(digit):
        buf += (9 * pow(10, i))
    if N == buf:
        print(9 * digit)
        sys.exit()
    buf = 0
    for i in range(digit - 1):
        buf += (9 * pow(10, i))
    if (N - digit_list[0] * pow(10, digit - 1)) == buf:
        cand = 0
        for ele in digit_list:
            cand += ele
        print(cand)
        sys.exit()
    cand = 0
    if digit_list[0] == 1:
        cand = 9 * (digit - 1)
    else:
        cand = digit_list[0] - 1 + 9 * (digit - 1)
    print(cand)

Submission status: Accepted

Solution code:
import math
n=int(input())
s = str(n)
array = list(map(int, list(s)))
a1=sum(array)
size = int (math.log10(n))
a2=int(n/(10**size))-1+size*9
print(max(a1,a2))

Submission status: Accepted

Solution code:
def num_sum(n):
	b = 0
	for i in range(16):
		a = n % 10
		b = b + a
		n = n // 10
	return b

x = int(input())
f = 0
for i in range(17):
	c = 10**(16-i)*(x//(10**(16-i))) -1
	if c <= 0:
		c = 0
	d = max(num_sum(x), num_sum(c), f)
	f = d
print(f)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def solve():
    N_str = raw_input()
    num_digits = len(N_str)
    N = int(N_str)

    ans = 0
    test = 10 ** num_digits - 1
    while True:
        base = 10 ** (num_digits - 1)
        for _ in xrange(10):
            if test <= N:
                ans = test
                break
            test -= base
        if ans:
            break

    print sum([int(d) for d in str(ans)])


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
N = list(input())

sum = 0

while N != []:
    if N[-1] != '9' and len(N) != 1:
        sum += 9
        del N[-1]
        if N[-1] == '0':
            N = list(str(int(''.join(N)) - 1))
        else:
            N[-1] = str(int(N[-1]) - 1)
    elif len(N) == 1:
        sum += int(N[0])
        del N[0]
    else:
        sum += 9
        del N[-1]

print(sum)

Submission status: Accepted

Solution code:
num = input()

counter = 0
lol = True

for i in range(1, len(num)):
    if int(num[i]) != 9:
        lol = False

if lol:
    counter += int(num[0])
else:
    counter += int(num[0]) - 1

counter += 9 * (len(num)-1)
print(counter)

Submission status: Accepted

Solution code:
N=int(input())
keta=len(str(N))
keta2=len(str(N+1))
alpha=int(str(N)[0])-1
beta=int(str(N+1)[0])-1
a=(keta-1)*9
if keta==1:
    print(N)
elif alpha==beta:
    print(a+alpha)
elif keta==keta2:
    print(a+beta)
else:
    print(keta*9)

Submission status: Accepted

Solution code:
n = input()
ls = list(map(int,[ _ for _ in n ]))
if int(n) <= 9:
    print(int(n))
elif sum(ls[1:]) / (len(ls)-1) == 9:
    print(sum(ls))
else:
    print(ls[0]-1 + 9*(len(ls)-1))

Submission status: Accepted

Solution code:
import random
import numpy
import sys
import copy

N=int(input())
m = 0
l = [9 for i in range(len(str(N)))]
for i in range(0,len(l)):
  s = copy.deepcopy(l)
  for j in range(9,-1,-1):
    s[i] = j
    num = int(''.join(map(str,s)))
    if num<=N:
      m=sum(s)
      print(m)
      exit()

Submission status: Accepted

Solution code:
import math
N = input()
n = int(N)
lst = list(N)
if len(lst)==1:
    print(int(lst[0]))
elif (n+1)%(10**(len(lst)-1)) == 0:
    print(int(lst[0])+9*(len(lst)-1))
else:
    print((int(lst[0])-1) + 9*(len(lst)-1))

Submission status: Accepted

Solution code:
#coding:utf-8
n = int(input())
num = len(str(n))
tmp = pow(10, num)-1
s = 0
for i in range(num+1):
    if i == num:
        s = sum(list(map(int, str(tmp-9*pow(10, num-1)+(int(str(n)[0])-1)*pow(10, num-1)))))
        break
    elif tmp-pow(10, i) <= n:
        s = sum(list(map(int, str(tmp-pow(10, i)))))
        break
if sum(list(map(int, str(n)))) > s:
    print(sum(list(map(int, str(n)))))
else:
    print(s)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
N = int(input())

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

a=[]

a.append(Sum(N))

N_str = str(N)
N_str = list(map(int, list(N_str)))

"右端の数字を1下げたときの最大"
N_str = str(N)
N_str = list(map(int, list(N_str)))
N_str[0] = N_str[0] - 1
for i in range(1,len(N_str)):
    N_str[i] = 9
a.append(sum(N_str))

print(max(a))

Submission status: Accepted

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

if all(N[i]=="9" for i in range(len(N))):
	ans=9*(len(N))

elif N[0]!="9" and all(N[i]=="9" for i in range(1,len(N))):
	for i in range(len(N)):
		ans+=int(N[i])

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

print(ans)

Submission status: Accepted

Solution code:
s = input()
if len(s) == 1:
    print(s)
else:
    t = set(s)
    if len(t) == 1 and "9" in t:
        print(len(s) * 9)
    elif len(t) == 2 and "9" in t and "0" not in t:
        if s[0] != "9":
            k = sorted(list(t))
            print((len(s) - 1) * 9 + int(k[0]))
        else:
            print((len(s) - 1) * 9 + 8)
    else:
        print(int(s[0]) + (len(s) - 1) * 9 - 1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
n = input()
result = sum(map(int, n))
acc = 0
for i, c in enumerate(n):
    if int(c):
        result = max(result, acc + (int(c) - 1) + (len(n) - i - 1) * 9)
    acc += int(c)
print(result)

Submission status: Accepted

Solution code:
# 100 => 99 => 18
# 9995 => 9989=> 35 9994
# 9944 => 9944 => 9939
# 9499 => 9499 => 8999
# 9444 => 8999
# 5444 => 4999 
# 994 => 989

N=int(raw_input())

dig=[]
rem = N

while rem>0:
    dig.append( rem % 10)
    rem = rem / 10

dig.reverse()

#print dig

for i in range(1, len(dig)):
    if dig[i] < 9:
        dig[i-1] = dig[i-1] - 1
        dig[i] = 9
        for j in range(i+1, len(dig)):
            dig[j] = 9
        break

#print dig

sum=0

for d in dig:
    sum = sum + d

print sum

Submission status: Accepted

Solution code:
n = int(input())

num = 0
for x in range(16):
    if n>=10**x and n<10**(x+1):
        num=x
        break
    else:
        num=16
out=0

if (n+1)//(10**(num)) == n//(10**(num)):
    out = n//10**(num) -1 + 9*num
else:
    out = n//10**(num) + 9*num
print(out)

Submission status: Accepted

Solution code:
import sys,collections;sys.setrecursionlimit(10**7)
def Is(): return [int(x) for x in sys.stdin.readline().split()]
def Ss(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

s = S()
n1 = sum([int(x) for x in s])
n2 = int(s[0])-1+9*(len(s)-1)
print(max(n1,n2))

Submission status: Accepted

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

def kazu(x):
    if x == 0:
        return 0,0
    else:
        a = x
        top = 0
        keta = 0
        while(a!=0):
            top = a
            a = a//10
            keta += 1
        return keta,top
#print(N,keta,top)

def digsum(x):
#    print(x)
    xketa, xtop = kazu(x)
 #   print(xketa, xtop)
    if x == 0:
        return 0
    else:
        xdown = x - (10**(xketa-1))*xtop
  #      print(xdown)
        return max((xtop -1) + 9*(xketa-1), xtop + digsum(xdown))
print(digsum(N))

Submission status: Accepted

Solution code:
N = int(input())
S = str(N)
L = list(S)

for x in range(len(L)):
    L[x] = int(L[x])

for x in range(1, len(L)):
    if L[x] != 9:
        L[x-1] -= 1

        for y in range(x, len(L)):
            L[y] = 9

res = 0

for x in L:
    res += x

print(res)

Submission status: Accepted

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

len_N=len(N)
sum_result=0

not_list_nine=[i for i in N if i != 9]
num_nine=len_N - len(not_list_nine)

N_first=N[0]

if N_first==9:
  if num_nine==len_N: sum_result=sum(N)
  else: sum_result=(len_N-1)*9+8
else:
  if num_nine==len_N-1: sum_result=sum(N)
  else: sum_result=(N_first-1)+(len_N-1)*9

print sum_result

Submission status: Accepted

Solution code:
def solve():
    inputstr = input()
    N = int(inputstr)
    L = len(inputstr)
    list = [dsum(mfloor(N,k)) for k in range(1,L)]
    list.append(dsum(N))
    ans = max(list)
    print(str(ans))

def dsum(n):
    ans = 0
    for d in str(n):
        ans += int(d)
    return ans

def mfloor(n,k):
    import math
    ans = math.floor(n/(10**k))*(10**k) - 1
    return ans

solve()

Submission status: Accepted

Solution code:
n = input()

if len(n) == 1:
    print(int(n))
else:
    if set(n[1:]) == {'9'}:
        print(sum(map(int, list(n))))
    else:
        print((int(n[0]) - 1) + (len(n) - 1) * 9)

Submission status: Accepted

Solution code:
string = input()
num = int(string)
n = list(map(int,list(string)))
total = sum(n)
if(len(n)==1):
    print(num)
else:
    digit_n = int(num/(10**(len(n)-1)))
    result = ((digit_n-1)+(len(n)-1)*9)
    print(result if result>total else total)

Submission status: Accepted

Solution code:
n = int(input())

top = 0
div = 10**16
digi = 17
while div >= 1:
  if n // div >= 1:
    top = n // div
    break
  div //= 10
  digi -= 1

res = 0
nine = div - 1
if n % div == nine:
  res = 9 * (digi - 1) + top
else:
  res = 9 * (digi - 1) + top - 1

print(res)