# Maximum money that can be withdrawn in two steps in C

We are given two lockers, say L1 and L2 that have some amount of money in the form of coins. L1 has A coins and L2 has B number of coins in it. We have to withdraw money or coins from the lockers such that the money drawn out is maximum. Each time the coins are drawn from any locker, it is replaced by coins 1 less than its previous count. If we draw A coins from L1 then it will be replaced by A-1 coins and if we draw B coins from L2 then it will be replaced by B-1 coins. The task is to maximize the amount of money withdrawn in two steps. That means the coins can be withdrawn only twice.

Input− L1 - 10, L2 - 11

Output −Maximum money that can be withdrawn in two steps − 21

Explanation − In step 1 we withdraw 11 coins from L2, L2 will be replaced by 11-1=10 coins.

In step 2 both L1 and L2 have 10 coins so can be withdrawn from any and we have 11+10=21 coins that is maximum.

Input − L1-5, L2-5

Output −Maximum money that can be withdrawn in two steps − 10

Explanation − In step 1 we withdraw 5 coins from L1, L1 will be replaced by 5-1=4 coins.

In step 2 both L1 has 4 coins and L2 has 5 coins so we take 5 coins from L2 and we have 5+5=10 coins that is maximum.

## Approach used in the below program is as follows

• We have two Lockers L1 and L2 as integers with some coins.

• Function maxMoney(int A, int B) takes as input the number of coins in lockers.

• Inside maxMoney() we take variable ‘money’ to store the maximum amount of money.

• Initially money takes the value from A or B whichever is more.(money=A>B?A:B)

• Compare the value of money with A or B to check which container’s coins are withdrawn.

• Now replace that container with 1 less than the previous amount. (A-- or B--)

• Again money will add the value from A or B whichever is more. (money+=A>B?A:B)

If k is smaller then the smallest k elements would have least sum −
• In D1 store the abs((sum of whole array) - (2*sum of least k elements)). Twice because array sum also has these elements.

If k is larger then the largest k elements would have highest sum −

• In D2 store the abs((sum of whole array) - (2*sum of highest k elements)). Twice because array sum also has these elements.

• Compare D1 with D2 and store maximum value in maxD.

• Return maxD as the result.

## Example

Live Demo

Code:
#include <stdio.h>
#include <math.h>
// Function to return the maximum coins we can get
int maxMoney(int A, int B){
//take coins
int money=A>B?A:B;
//refill the lockers with 1 less no.of coins
if(money==A)
A--;
else
B--;
//withdraw again
money+=A>B?A:B;
return money;
}
// Driver code
int main(){
int L1 = 8, L2 = 9;
printf("Maximum money that can be withdrawn in two steps: %d" , maxMoney(L1, L2));
return 0;
}

## Output

If we run the above code it will generate the following output −

Maximum money that can be withdrawn in two steps: 17