TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
coin_change.cpp
1#include <climits>
2#include <iostream>
3#include <vector>
4using namespace std;
5
6// Function to find the Minimum number of coins required to get Sum S
7int findMinCoins(int arr[], int n, int N) {
8 // dp[i] = no of coins required to get a total of i
9 std::vector<int> dp(N + 1);
10
11 // 0 coins are needed for 0 sum
12
13 dp[0] = 0;
14
15 for (int i = 1; i <= N; i++) {
16 // initialize minimum number of coins needed to infinity
17 dp[i] = INT_MAX;
18 int res = INT_MAX;
19
20 // do for each coin
21 for (int c = 0; c < n; c++) {
22 if (i - arr[c] >=
23 0) // check if coins doesn't become negative by including it
24 res = dp[i - arr[c]];
25
26 // if total can be reached by including current coin c,
27 // update minimum number of coins needed dp[i]
28 if (res != INT_MAX)
29 dp[i] = min(dp[i], res + 1);
30 }
31 }
32
33 // The Minimum No of Coins Required for N = dp[N]
34 return dp[N];
35}
36
37int main() {
38 // No of Coins We Have
39 int arr[] = {1, 2, 3, 4};
40 int n = sizeof(arr) / sizeof(arr[0]);
41
42 // Total Change Required
43 int N = 15;
44
45 cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N)
46 << "\n";
47
48 return 0;
49}
int main()
Main function.
for std::vector
constexpr uint32_t N
A struct to represent sparse table for min() as their invariant function, for the given array A....