I have encountered the minimum coin change problem on CodeChef and CodeForces. On both sites I have submitted my implementation using DP. This implementation given TLE error on both sites.
Unfortunately, I cannot find any other implementation of this problem.
I am linking the problems -
CodeChef - https://www.codechef.com/problems/FLOW005
CodeForces - https://codeforces.com/problemset/problem/996/A
Here is my code(CodeChef implementation) -
int main() {
int T{};
std::cin >> T;
for (int i = 1; i <= T; ++i) {
int N{};
std::cin >> N;
std::vector <int> arr(N + 1);
for (int i = 0; i < N + 1; ++i) {
arr[i] = minCoins(i, arr);
}
std::cout << arr[N] << std::endl;
}
return 0;
}
The minCoins Function -
int minCoins(int x, std::vector <int> arr) {
if (x == 0)
return 0;
else if (x == 1 || x == 2 || x == 5 || x == 10 || x == 50 || x == 100)
return 1;
int min{ 1 + arr[x - 1]};
if (x > 100)
min = std::min(min, l + arr[x - 100]);
if (x > 50)
min = std::min(min, 1 + arr[x - 50]);
if (x > 10)
min = std::min(min, 1 + arr[x - 10]);
if (x > 5)
min = std::min(min, 1 + arr[x - 5]);
if (x > 2)
min = std::min(min, 1 + arr[x - 2]);
if (x > 1)
min = std::min(min, 1 + arr[x - 1]);
return min;
}
There is no problem of integer overflow as I chose int data type after reading the constraints. Also, if anyone would like to suggest how I can remove the if ladder and replace it with something simpler, I would appreciate the help. Also, thank you for taking the time to read my question :)