Maximizing cakes on a journey
Last Updated :
13 Sep, 2023
A man starts from his house with a few cakes. let them be N. Now he visits K places before reaching home. At each place, he can buy a cake, sell a cake or do nothing. But he must sell L cakes before reaching home. Find the maximum number of cakes he can have at any point in his journey. N, K, and L are given as input which is the cakes he has before starting, the number of places visited, and the number of cakes he has to sell respectively.
Examples:
Input: N = 5, K = 3, L = 1
Output: 7
Explanation: First we will buy 2 cakes to make a total of 7 then we will sell 1 cake.
Input: N = 1, K = 4, L = 3
Output: -1
Explanation: There is no way we will have a cake to sell at last place.
Approach: To solve the problem follow the below observations:
Observations:
- We have K places to visit and at L places we have to sell, for getting the maximum number of cakes at a time we will first buy cakes to reach the maximum, and then at last L places, we will sell the cakes.
- In order to do this we have to make sure that at the particular time, we will have a cake when we have to sell. For this, we will find the number of places we can buy cakes which is BuyCakes = K-L (places to visit – places to sell).
- Then we will check if the sum of N and BuyCakes is less than L, then return -1.
Below is the implementation of the above idea.
C++
#include <iostream>;
using namespace std;
int maxCakes( int N, int K, int L)
{
int BuyCakes = K - L;
if (N + BuyCakes < L) {
return -1;
}
else {
return BuyCakes + N;
}
}
int main()
{
int N = 5;
int K = 3;
int L = 1;
cout << maxCakes(N, K, L) << endl;
return 0;
}
|
Java
class GFG {
static int maxCakes( int N, int K, int L)
{
int BuyCakes = K - L;
if (N + BuyCakes < L) {
return - 1 ;
}
else {
return BuyCakes + N;
}
}
public static void main(String[] args)
{
int N = 5 ;
int K = 3 ;
int L = 1 ;
System.out.println(maxCakes(N, K, L));
}
}
|
Python3
def maxCakes(N, K, L):
BuyCakes = K - L
if N + BuyCakes & lt
L:
return ( - 1 )
else :
return (BuyCakes + N)
N = 5
K = 3
L = 1
print (maxCakes(N, K, L))
|
C#
using System;
class GFG {
static int maxCakes( int N, int K, int L)
{
int BuyCakes = K - L;
if (N + BuyCakes < L) {
return -1;
}
else {
return BuyCakes + N;
}
}
public static void Main(String[] args)
{
int N = 5;
int K = 3;
int L = 1;
Console.WriteLine(maxCakes(N, K, L));
}
}
|
Javascript
function maxCakes(N, K, L) {
let BuyCakes = K - L;
if (N + BuyCakes < L) {
return -1;
} else {
return BuyCakes + N;
}
}
let N = 5;
let K = 3;
let L = 1;
console.log(maxCakes(N, K, L));
|
Time Complexity: O(1),
Auxiliary Space: O(1).
Share your thoughts in the comments
Please Login to comment...