Maximum money that can be withdrawn in two steps
Last Updated :
07 Jun, 2022
There are two cash lockers, one has X number of coins and the other has Y number of coins, you can withdraw money at max two times, when you withdraw from a locker you will get the total money of the locker and the locker will be refilled with Z – 1 coin if it had Z coins initially. The task is to find the maximum coins you can get.
Examples:
Input: X = 6, Y = 3
Output: 11
Take from locker X i.e. 6
Now, X = 5 and Y = 3
Take again from locker X i.e. 5.
Input: X = 4, Y = 4
Output: 8
Approach: In order to maximize the number of coins, take from the locker which has the maximum value then update the locker and again take from the locker with the maximum value.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxCoins( int X, int Y)
{
if (X < Y)
swap(X, Y);
int coins = X;
X--;
coins += max(X, Y);
return coins;
}
int main()
{
int X = 7, Y = 5;
cout << maxCoins(X, Y);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int maxCoins( int X, int Y)
{
if (X < Y) {
swap(X, Y);
}
int coins = X;
X--;
coins += Math.max(X, Y);
return coins;
}
static void swap( int X, int Y)
{
int temp = X;
X = Y;
Y = temp;
}
public static void main(String[] args)
{
int X = 7 , Y = 5 ;
System.out.println(maxCoins(X, Y));
}
}
|
Python3
def maxCoins(X, Y) :
if (X < Y) :
X, Y = Y, X;
coins = X;
X - = 1 ;
coins + = max (X, Y);
return coins;
if __name__ = = "__main__" :
X = 7 ; Y = 5 ;
print (maxCoins(X, Y));
|
C#
using System;
class GFG {
static int maxCoins( int X, int Y)
{
if (X < Y) {
swap(X, Y);
}
int coins = X;
X--;
coins += Math.Max(X, Y);
return coins;
}
static void swap( int X, int Y)
{
int temp = X;
X = Y;
Y = temp;
}
public static void Main(String[] args)
{
int X = 7, Y = 5;
Console.WriteLine(maxCoins(X, Y));
}
}
|
PHP
<?php
function maxCoins( $X , $Y )
{
if ( $X < $Y )
swap( $X , $Y );
$coins = $X ;
$X --;
$coins += max( $X , $Y );
return $coins ;
}
$X = 7;
$Y = 5;
echo maxCoins( $X , $Y );
?>
|
Javascript
<script>
function maxCoins(X, Y)
{
if (X < Y) {
let temp = X;
X = Y;
Y = temp;
}
let coins = X;
X--;
coins += Math.max(X, Y);
return coins;
}
let X = 7, Y = 5;
document.write(maxCoins(X, Y));
</script>
|
Time Complexity: O(1), as there is no loop.
Auxiliary Space: O(1), as no extra space has been taken.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...