Given a number N, the task is to find the maximum number of steps convert N to zero where in each step a number m (1 < m < N (initial value of N)) is subtracted from N. If it is impossible to convert N to 0 in this way print -1.
Note: Values of m can be different in different steps.
Examples:
Input: N = 14
Output: 7
Explanation: The steps are as shown below:
14 – 2 = 12 – 1st Operation
12 – 2 = 10 – 2nd Operation
10 – 2 = 8 – 3rd Operation
8 – 2 = 6 – 4th Operation
6 – 2 = 4 – 5th operation
4 -2 = 2 – 6th Operation
2-2 = 0 – 7th Operation
Input: N = 2
Output: -1
Explanation: Not possible to obtain 0
Input: N = 5
Output: 2
Explanation: Subtract 2 and 3 from 5 respectively
Approach: The problem can be solved based on simple observation. If N = 1, 2 or 3 there is no possible way to obtain 0 from N. In all other cases there is a possible way. The number of steps will be maximum when the minimum value will be subtracted in each step i.e. 2. So the total number of steps becomes N/2. (When N is odd the last subtracted value will be 3 because 1 is not allowed)
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int minSteps( int N)
{
if (N == 1 || N == 2 || N == 3)
return -1;
return (N / 2);
}
int main()
{
int N;
N = 5;
cout << minSteps(N);
return 0;
}
|
Java
class GFG
{
static int minSteps( int N)
{
if (N == 1 || N == 2 || N == 3 )
return - 1 ;
return (N / 2 );
}
public static void main(String args[])
{
int N;
N = 5 ;
System.out.println(minSteps(N));
}
}
|
Python3
def minSteps (N):
if (N = = 1 or N = = 2 or N = = 3 ):
return - 1 ;
return N / / 2 ;
N = 5 ;
print (minSteps(N));
|
C#
using System;
class GFG
{
static int minSteps( int N)
{
if (N == 1 || N == 2 || N == 3)
return -1;
return (N / 2);
}
public static void Main()
{
int N;
N = 5;
Console.WriteLine(minSteps(N));
}
}
|
Javascript
<script>
const minSteps = (N) => {
if (N == 1 || N == 2 || N == 3)
return -1;
return parseInt(N / 2);
}
let N;
N = 5;
document.write(minSteps(N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)