CSES - Minimizing Coins
Authors: Michael Cao, Sofia Yang, Paul Chen
Explanation
In this problem, we're asked the minimum number of coins of distinct weights needed to achieve some weight, . You can read about the solution to this classical problem in CPH Chapter 7 under "Coin Problem".
For this problem, we'll define as the minimum number of coins to achieve some weight, . Then, at some , we can try to use every coin. Using the -th coin represents transitioning from the state where represents the value of the -th coin. So, for , the transition is:
Finally, the base case would be , since it requires coins to get a sum of .
Warning!
Remember to initialize the array with some large value, since we
are computing a minimum. Additionally, if is an int
array, don't
initialize with INT_MAX
, since that could cause overflow when
you add 1 for the transitions.
Implementation
Warning!
Don't forget to check if , where is the large value you used, and print if so (since it's impossible to achieve a sum of ).
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;using ll = long long;ll dp[1000001];const int MOD = 1e9 + 7;int main() {int n, x;
Java
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.StringTokenizer;public class MinCoins {public static int MAX = (int)10e6 + 2;public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Python
INF = 1000000000 # Using float('inf') results in a TLEn, x = map(int, input().split())c = list(map(int, input().split()))dp = [INF] * (x + 1)dp[0] = 0 # Base case: 0 coins are needed for a sum of 0for coin in c:for i in range(x - coin + 1):
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!