Given an integer N, the task is to check if N can be expressed as a sum of integers having 9 as the last digit (9, 19, 29, 39…), or not. If found to be true, then find the minimum count of such integers required to obtain N. Otherwise print -1.
Examples:
Input: N = 156
Output: 4
Explanation:
156 = 9 + 9 + 9 + 129
Input: N = 60
Output: -1
Explanation:
No possible way to obtain sum 60 from numbers having 9 as the last digit.
Naive Approach: This problem can be viewed as a variation of the Coin change problem. For this problem, the coins can be replaced with [9, 19, 29, 39…. up to the last number smaller than N that ends with 9].
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized based on the observation that if the last digit of N is K, then exactly (10 – K) minimum numbers are required to form N.
A sum N can be obtained by adding 10 – K numbers, where K is the last digit of N.
Therefore, sum N can be obtained by adding 9, (9 – K) times and adding N – (9 * (9 – K)) finally.
Follow the steps below to solve the problem:
- Extract the last digit of the given number, K = N % 10
- Using the above observation, a total of (10 – K) numbers are required. Now, calculate 9 * (9 – K), as the first 9 – K numbers required to obtain N is 9.
- Now, calculate N – 9 * (9 – K) and store in a variable, say z. If z is greater than or equal to 9 and has 9 as its last digit, print 10 – K as the answer. Otherwise, print -1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minCountOfNumbers( int N)
{
int k = N % 10;
int z = N - (9 * (9 - k));
if (z >= 9 && z % 10 == 9) {
return 10 - k;
}
else
return -1;
}
int main()
{
int N = 156;
cout << minCountOfNumbers(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int minCountOfNumbers( int N)
{
int k = N % 10 ;
int z = N - ( 9 * ( 9 - k));
if (z >= 9 && z % 10 == 9 )
{
return 10 - k;
}
else
return - 1 ;
}
public static void main(String[] args)
{
int N = 156 ;
System.out.print(minCountOfNumbers(N));
}
}
|
Python3
def minCountOfNumbers(N):
k = N % 10
z = N - ( 9 * ( 9 - k))
if (z > = 9 and z % 10 = = 9 ):
return 10 - k
else :
return - 1
if __name__ = = '__main__' :
N = 156
print (minCountOfNumbers(N))
|
C#
using System;
class GFG{
static int minCountOfNumbers( int N)
{
int k = N % 10;
int z = N - (9 * (9 - k));
if (z >= 9 && z % 10 == 9)
{
return 10 - k;
}
else
return -1;
}
public static void Main(String[] args)
{
int N = 156;
Console.Write(minCountOfNumbers(N));
}
}
|
Javascript
<script>
function minCountOfNumbers(N){
let k = N % 10;
let z = N - (9 * (9 - k));
if (z >= 9 && z % 10 == 9)
{
return 10 - k;
}
else
{
return -1;
}
}
let N = 156;
document.write(minCountOfNumbers(N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)