给定两个整数A和B ,任务是通过将A增加或减少1 、 2或5任意次数来找到使A等于B所需的最小移动次数。
例子:
Input: A = 4, B = 0
Output: 2
Explanation:
Perform the operation as follows:
- Decreasing the value of A by 2, modifies the value of A to (4 – 2) = 2.
- Decreasing the value of A by 2 modifies the value of A to (2 – 2) = 0. Which is equal to B.
Therefore, the number of moves required is 2.
Input: A = 3, B = 9
Output: 2
方法:可以使用贪心方法解决给定的问题。这个想法是首先找到5的增量或减量,然后是2 ,然后需要1将A转换为B 。请按照以下步骤解决问题:
- 将A的值更新为A和B之间的绝对差值。
- 现在,打印(A/5) + (A%5)/2 + (A%5)%2 的值作为将A转换为B的最小增量或减量1 、 2或5 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find minimum number of
// moves required to convert A into B
int minimumSteps(int a, int b)
{
// Stores the minimum number of
// moves required
int cnt = 0;
// Stores the absolute
// differenece
a = abs(a - b);
// FInd the number of moves
cnt = (a / 5) + (a % 5) / 2 + (a % 5) % 2;
// Return cnt
return cnt;
}
// Driver Code
int main()
{
// Input
int A = 3, B = 9;
// Function call
cout << minimumSteps(A, B);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG
{
// Function to find minimum number of
// moves required to convert A into B
static int minimumSteps(int a, int b)
{
// Stores the minimum number of
// moves required
int cnt = 0;
// Stores the absolute
// differenece
a = Math.abs(a - b);
// FInd the number of moves
cnt = (a / 5) + (a % 5) / 2 + (a % 5) % 2;
// Return cnt
return cnt;
}
// Driver Code
public static void main(String[] args)
{
// Input
int A = 3, B = 9;
// Function call
System.out.println(minimumSteps(A, B));
}
}
// This code is contributed by Potta Lokesh
Python3
# python program for the above approach
# Function to find minimum number of
# moves required to convert A into B
def minimumSteps(a, b):
# Stores the minimum number of
# moves required
cnt = 0
# Stores the absolute
# differenece
a = abs(a - b)
# FInd the number of moves
cnt = (a//5) + (a % 5)//2 + (a % 5) % 2
# Return cnt
return cnt
# Driver Code
# Input
A = 3
B = 9
# Function call
print(minimumSteps(A, B))
# This code is contributed by amreshkumar3.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find minimum number of
// moves required to convert A into B
static int minimumSteps(int a, int b)
{
// Stores the minimum number of
// moves required
int cnt = 0;
// Stores the absolute
// differenece
a = Math.Abs(a - b);
// FInd the number of moves
cnt = (a / 5) + (a % 5) / 2 + (a % 5) % 2;
// Return cnt
return cnt;
}
// Driver Code
public static void Main()
{
// Input
int A = 3, B = 9;
// Function call
Console.Write(minimumSteps(A, B));
}
}
// This code is contributed by SURENDRA_GANGWAR
Javascript
输出
2
时间复杂度: O(1)
辅助空间: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。