给定N个大糖果和M个小糖果。可以通过支付X小糖果来购买一个大糖果。或者,可以将一个大糖果出售为Y个小糖果。任务是找到可以购买的最大数量的大糖果。
例子:
Input: N = 3, M = 10, X = 4, Y = 2
Output: 5
8 small candies are exchanged for 2 big candies.
Input: N = 3, M = 10, X = 1, Y = 2
Output: 16
Sell all the initial big candies to get 6 small candies.
Now 16 small candies can be exchanged for 16 big candies.
在第一个示例中,无法出售大糖果来牟利。因此,只有剩余的小糖果可以换成大糖果。
在第二个示例中,可以出售大糖果以获取利润。
方法:如果最初的大糖果可以被出售以获利,即X
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the maximum big
// candies that can be bought
int max_candies(int bigCandies,
int smallCandies,int X, int Y)
{
// If initial big candies
// can be sold for profit
if (X < Y)
{
smallCandies += Y * bigCandies;
bigCandies = 0;
}
// Update big candies that can be bought
bigCandies += (smallCandies / X);
return bigCandies;
}
// Driver code
int main()
{
int N = 3, M = 10;
int X = 4, Y = 2;
cout << (max_candies(N, M, X, Y));
return 0;
}
Java
// Java implementation of the approach
class GFG {
// Function to return the maximum big candies
// that can be bought
static int max_candies(int bigCandies, int smallCandies,
int X, int Y)
{
// If initial big candies can be sold for profit
if (X < Y) {
smallCandies += Y * bigCandies;
bigCandies = 0;
}
// Update big candies that can be bought
bigCandies += (smallCandies / X);
return bigCandies;
}
// Driver code
public static void main(String[] args)
{
int N = 3, M = 10;
int X = 4, Y = 2;
System.out.println(max_candies(N, M, X, Y));
}
}
Python3
# Python3 implementation of the approach
# Function to return the maximum big candies
# that can be bought
def max_candies(bigCandies, smallCandies, X, Y):
# If initial big candies can
# be sold for profit
if(X < Y):
smallCandies += Y * bigCandies
bigCandies = 0
# Update big candies that can be bought
bigCandies += (smallCandies // X)
return bigCandies
# Driver code
N = 3
M = 10
X = 4
Y = 2
print(max_candies(N, M, X, Y))
# This code is contributed by Code_Mech
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the maximum
// big candies that can be bought
static int max_candies(int bigCandies,
int smallCandies,
int X, int Y)
{
// If initial big candies
// can be sold for profit
if (X < Y)
{
smallCandies += Y * bigCandies;
bigCandies = 0;
}
// Update big candies that can be bought
bigCandies += (smallCandies / X);
return bigCandies;
}
// Driver code
static public void Main ()
{
int N = 3, M = 10;
int X = 4, Y = 2;
Console.WriteLine(max_candies(N, M, X, Y));
}
}
// This Code is contributed by ajit...
PHP
输出:
5