通过在每个步骤中减去除 1 和 N 之外的任何值来最大化步骤以将 N 减少到 0
给定一个数字N ,任务是找到将N转换为零的最大步骤数,其中在每个步骤中从N中减去一个数字m ( 1 < m < N (N 的初始值))。如果无法以这种方式将N转换为0 ,请打印-1 。
注意: m的值在不同的步骤中可能不同。
例子:
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
方法:问题可以通过简单的观察来解决。如果N = 1、2 或 3 ,则无法从N获得0 。在所有其他情况下,都有可能的方法。当每个步骤中减去最小值时,步骤数将最大,即2 。因此总步数变为N/2 。 (当 N 为奇数时,最后减去的值为 3,因为不允许 1)
下面是上述方法的实现。
C++
// C++ code to implement above approach
#include
using namespace std;
// Function to find
// the minimum number of steps
int minSteps(int N)
{
if (N == 1 || N == 2 || N == 3)
return -1;
return (N / 2);
}
// Driver code
int main()
{
int N;
N = 5;
cout << minSteps(N);
return 0;
}
Java
// Java code to implement above approach
class GFG
{
// Function to find
// the minimum number of steps
static int minSteps(int N)
{
if (N == 1 || N == 2 || N == 3)
return -1;
return (N / 2);
}
// Driver Code:
public static void main(String args[])
{
int N;
N = 5;
System.out.println(minSteps(N));
}
}
// This code is contributed by gfgking
Python3
# Python code to implement above approach
# Function to find
# the minimum number of steps
def minSteps (N):
if (N == 1 or N == 2 or N == 3):
return -1;
return N // 2;
# Driver code
N = 5;
print(minSteps(N));
# This code is contributed by gfgking
C#
// C# code to implement above approach
using System;
class GFG
{
// Function to find
// the minimum number of steps
static int minSteps(int N)
{
if (N == 1 || N == 2 || N == 3)
return -1;
return (N / 2);
}
// Driver Code:
public static void Main()
{
int N;
N = 5;
Console.WriteLine(minSteps(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
2
时间复杂度: O(1)
辅助空间: O(1)