python coding test course, greedy algorithm

Problem Description

The problem we will address today is the Coin Change Problem. This problem involves finding the least number of coins needed to make a specific amount using various coins that we often encounter in real life.

Problem Definition

Write a function min_coins(coins, amount) that satisfies the following conditions:

  • coins: A list of available coins (e.g., [1, 5, 10, 25])
  • amount: The target amount to be formed

This function should return the minimum number of coins needed to make the given amount. If it is not possible to use the coins, it should return -1.

Understanding the Problem

To understand the problem more deeply, let’s look at a few examples.

Example 1:
Input: coins = [1, 5, 10, 25], amount = 63
Output: 6
Explanation: 25 + 25 + 10 + 1 + 1 + 1 = 63
Example 2:
Input: coins = [2, 4], amount = 5
Output: -1
Explanation: There are no ways to form 5.

Approach

To solve this problem, we will use a greedy algorithm. The greedy algorithm works by making the best choice in the current situation. Therefore, we will start by using the largest coins sequentially to try to form the target amount.

The specific steps of the algorithm are as follows:

  1. Sort the available coins in descending order.
  2. Compare the current amount with the coins and use as many coins as possible.
  3. Repeat this process until the remaining amount is zero.
  4. If the remaining amount is zero, return the number of coins, otherwise return -1.

Code Implementation

Now, let’s write the code based on this approach:


def min_coins(coins, amount):
    # Sort the coins in descending order
    coins.sort(reverse=True)
    
    count = 0  # Number of coins used
    
    for coin in coins:
        # Ignore if the current coin is greater than amount
        while amount >= coin:
            amount -= coin  # Subtract the coin value from amount
            count += 1  # Increase the coin count
            
    # Check if the final amount is 0
    return count if amount == 0 else -1
    

Testing

Now, let’s test the function we have written.


# Test cases
print(min_coins([1, 5, 10, 25], 63))  # 6
print(min_coins([2, 4], 5))             # -1
print(min_coins([5, 2, 1], 11))         # 3 (5 + 5 + 1)
    

Conclusion

We have solved the Coin Change Problem using the greedy algorithm. Through this problem, we learned the fundamental approach of the greedy algorithm and studied a common type of problem seen in coding tests.

I hope to deepen my understanding of the greedy algorithm by practicing more problems. Like the problem above, it is essential to practice how to sort data and use loops to find solutions. The greedy algorithm can be a useful tool for solving various problems.

Thank you!