Biggest integer which has maximum digit sum in range from 1 to n - GeeksforGeeks

22 Apr, 2021
Given a number n, find a number in range from 1 to n such that its sum is maximum. If there are several such integers, determine the biggest of them.
Examples : 
Input:  n = 100
Output: 99  
99 is the largest number in range from
1 to 100 with maximum sum of digits.

Input: n = 48
Output: 48
Explanation: 
There are two numbers with maximum
digit sum. The numbers are 48 and 39
Since 48 > 39, it is our answer.
A naive approach is to iterate for all numbers from 1 to n and find out which number has maximum sum of digits. Time complexity of this solution is O(n).
An efficient approach is to iterate from n to 1. Do the following for each digit of current number, if the digit is not zero, reduce it by one and change all other digits to nine to the right of it. If the sum of digits in the resulting integer is strictly greater than the sum of the digits of the current answer, then update the answer with the resulting integer. If the sum of the resulting integer is same as the current answer, then if the resulting integer is more then current answer, update the current answer with the resulting integer.
How to reduce a digit and change all other digits on its right to 9? Let x be our current number. We can find next number for current digit using below formula. In below formula, b is a power of 10 to represent position of current digit. After every iteration we reduce x to x/10 and change b to b * 10.We use (x – 1) * b + (b – 1); 
This line can further be explained as, if the number is x = 521 and b = 1, then  
(521 – 1) * 1 + (1-1) which gives you 520, which is the thing we need to do, reduce the position number by 1 and replace all other numbers to the right by 9.
After x /= 10 gives you x as 52 and b*=10 gives you b as 10, which is again executed as (52-1)*(10) + 9 which gives you 519, which is what we have to do, reduce the current index by 1 and increase all other rights by 9.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the// number with maximum digit// sum.#include <bits/stdc++.h>using namespace std; // function to calculate the // sum of digits of a number.int sumOfDigits(int a){    int sum = 0;    while (a)    {        sum += a % 10;        a /= 10;    }    return sum;} // Returns the maximum number// with maximum sum of digits.int findMax(int x){    // initializing b as 1 and    // initial max sum to be of n    int b = 1, ans = x;     // iterates from right to    // left in a digit    while (x)    {         // while iterating this        // is the number from        // from right to left        int 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) ||           (sumOfDigits(cur) == sumOfDigits(ans) &&            cur > ans))            ans = cur;         // reduces the number to one unit less        x /= 10;        b *= 10;    }     return ans;} // driver programint main(){    int n = 521;    cout << findMax(n);    return 0;}
// Java program to find the// number with maximum digit// sum.import java.io.*; class GFG {         // function to calculate the     // sum of digits of a number.      static int sumOfDigits(int a)    {        int sum = 0;        while (a!=0)        {            sum += a % 10;            a /= 10;        }        return sum;    }         // Returns the maximum number    // with maximum sum of digits.    static int findMax(int x)    {        // initializing b as 1 and        // initial max sum to be of n        int b = 1, ans = x;             // iterates from right to        // left in a digit        while (x!=0)        {                 // while iterating this            // is the number from            // from right to left            int 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) ||            (sumOfDigits(cur) == sumOfDigits(ans) &&                cur > ans))                ans = cur;                 // reduces the number to one unit less            x /= 10;            b *= 10;        }             return ans;    }         // driver program    public static void main (String[] args)    {        int n = 521;        System.out.println(findMax(n));    }} /*This article is contributed by Nikita Tiwari.*/
# Python 3 program to# find the number# with maximum digit# sum.  # function to calculate# the sum of digits of# a number.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     # driver program to test the above functionn = 521print(findMax(n)) # This article is contributed by Nikita Tiwari.
// C# program to find the number// with maximum digit sum.using System; class GFG {          // function to calculate the     // sum of digits of a number.      static int sumOfDigits(int a)    {        int sum = 0;        while (a!=0)        {            sum += a % 10;            a /= 10;        }        return sum;    }          // Returns the maximum number    // with maximum sum of digits.    static int findMax(int x)    {        // initializing b as 1 and        // initial max sum to be of n        int b = 1, ans = x;              // iterates from right to        // left in a digit        while (x!=0)        {                  // while iterating this            // is the number from            // from right to left            int 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) ||               (sumOfDigits(cur) == sumOfDigits(ans) &&                                            cur > ans))                ans = cur;                  // reduces the number to one unit less            x /= 10;            b *= 10;        }              return ans;    }          // driver program    public static void Main()    {        int n = 521;        Console.WriteLine(findMax(n));    }}  // This article is contributed by Anant Agarwal.
<?php// PHP program to find the// number with maximum digit// sum. // function to calculate the// sum of digits of a number.function sumOfDigits($a){    $sum = 0;    while ($a)    {        $sum += $a % 10;        $a = (int)$a / 10;    }    return $sum;} // Returns the maximum number// with maximum sum of digits.function 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)    {         // while iterating this        // is the number from        // 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) ||           (sumOfDigits($cur) == sumOfDigits($ans) &&                                        $cur > $ans))            $ans = $cur;         // reduces the number        // to one unit less        $x = (int)$x / 10;        $b *= 10;    }     return $ans;} // Driver Code$n = 521;echo findMax($n); // This code is contributed by ajit?>
<script> // Javascript program to find the// number with maximum digit// sum. // Function to calculate the// sum of digits of a number.function sumOfDigits(a){    var sum = 0;    while (a != 0)    {        sum += a % 10;        a = parseInt(a / 10);    }    return sum;} // Returns the maximum number// with maximum sum of digits.function findMax(x){         // Initializing b as 1 and    // initial max sum to be of n    var b = 1, ans = x;     // Iterates from right to    // left in a digit    while (x != 0)    {                 // While iterating this        // is the number from        // from right to left        var 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) ||           (sumOfDigits(cur) ==            sumOfDigits(ans) &&            cur > ans))            ans = cur;         // Reduces the number to one unit less        x = parseInt(x / 10);        b *= 10;    }    return ans;} // Driver Codevar n = 521; document.write(findMax(n)); // This code is contributed by todaysgaurav </script>
Output : 
499
Time complexity : O(m) where m is the number of digits in n.
This article is contributed by Striver. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
jit_t
todaysgaurav
number-digits
Numbers
Mathematical
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Singular Value Decomposition (SVD)
Check if a number is Palindrome
Segment Tree | Set 1 (Sum of given range)
How to check if a given point lies inside or outside a polygon?
Program to multiply two matrices
Count ways to reach the n'th stair
Merge two sorted arrays with O(1) extra space