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.

Syntax

int maxMoney(int A, int B);

Approach

The 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.
  • 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.
  • Again money will add the value from A or B whichever is more.

Example

Let's see how this works with an example −

#include <stdio.h>

// Function to return the maximum coins we can get
int maxMoney(int A, int B) {
    // Take coins from the locker with more coins
    int money = A > B ? A : B;
    
    // Refill the lockers with 1 less number of coins
    if (money == A)
        A--;
    else
        B--;
    
    // Withdraw again from the locker with more coins
    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<br>", maxMoney(L1, L2));
    
    // Test with different values
    L1 = 10; L2 = 11;
    printf("Maximum money for L1=%d, L2=%d: %d<br>", L1, L2, maxMoney(L1, L2));
    
    L1 = 5; L2 = 5;
    printf("Maximum money for L1=%d, L2=%d: %d<br>", L1, L2, maxMoney(L1, L2));
    
    return 0;
}
Maximum money that can be withdrawn in two steps: 17
Maximum money for L1=10, L2=11: 21
Maximum money for L1=5, L2=5: 10

How It Works

For the example with L1=8 and L2=9 −

  • Step 1: Withdraw 9 coins from L2 (larger value), L2 becomes 8
  • Step 2: Both lockers have 8 coins, withdraw 8 from either
  • Total: 9 + 8 = 17 coins

The strategy is always to withdraw from the locker with maximum coins in each step to ensure maximum total withdrawal.

Conclusion

The maximum money withdrawal problem is solved by using a greedy approach where we always withdraw from the locker containing more coins. This ensures optimal results in exactly two withdrawal steps.

Updated on: 2026-03-15T13:00:45+05:30

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements