-
Notifications
You must be signed in to change notification settings - Fork 2
/
GetMinimalNumberOfCoinsInChange.cpp
98 lines (77 loc) · 2.86 KB
/
GetMinimalNumberOfCoinsInChange.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
T(n, k) = O(n * k)
M(n, k) = O(k)
n - liczba nominałów
k - kwota
*/
#include <limits.h>
#include <algorithm>
#include <iostream>
class CurrentChange {
public:
bool possible;
int coinsCount;
CurrentChange(bool possible, int coinsCount) {
this->possible = possible;
this->coinsCount = coinsCount;
}
};
CurrentChange** GetChangesTable(int change) {
CurrentChange** changes = new CurrentChange*[change + 1];
changes[0] = new CurrentChange(true, 0);
return changes;
}
void FindPossibleChanges(int coins[], int coinsSize, int change, CurrentChange** changes) {
for (int currentChange = 1; currentChange <= change; currentChange++) {
changes[currentChange] = new CurrentChange(false, INT_MAX);
for (int coinIndex = 0; coinIndex < coinsSize; coinIndex++) {
if (currentChange == coins[coinIndex] || (currentChange > coins[coinIndex] && changes[currentChange - coins[coinIndex]]->possible)) {
changes[currentChange]->possible = true;
break;
}
}
}
}
void CountCoins(int coins[], int coinsSize, int change, CurrentChange** changes) {
for (int currentChange = 1; currentChange <= change; currentChange++) {
if (!changes[currentChange]->possible)
continue;
for (int coinIndex = 0; coinIndex < coinsSize; coinIndex++) {
if (currentChange < coins[coinIndex] || !changes[currentChange - coins[coinIndex]]->possible)
continue;
if (currentChange == coins[coinIndex]) {
changes[currentChange]->coinsCount = 1;
break;
}
changes[currentChange]->coinsCount = std::min(
changes[currentChange - coins[coinIndex]]->coinsCount + 1,
changes[currentChange]->coinsCount);
}
}
}
void Print(int change, CurrentChange** changes) {
for (int i = 0; i <= change; i++) {
std::cout << i << ":\t" << changes[i]->coinsCount << "\n";
}
}
void DeleteChanges(CurrentChange** changes, int change) {
for (int i = 0; i <= change; i++) {
delete changes[i];
}
delete[] changes;
}
int GetMinimalNumberOfCoinsInChange(int coins[], int coinsSize, int change, bool debug) {
if (coins[0] < 1 || coinsSize < 1)
return -1;
CurrentChange** changes = GetChangesTable(change);
FindPossibleChanges(coins, coinsSize, change, changes);
CountCoins(coins, coinsSize, change, changes);
int minimalNumberOfCoinsInChange = changes[change]->coinsCount;
if (debug) Print(change, changes);
DeleteChanges(changes, change);
return minimalNumberOfCoinsInChange;
}
int main() {
std::cout << GetMinimalNumberOfCoinsInChange(new int[4]{2, 3, 20, 50}, 4, 21, false) << "\n";
std::cout << GetMinimalNumberOfCoinsInChange(new int[4]{2, 3, 20, 50}, 4, 80, true) << "\n";
}