In other words, given a set of n positive integers A
and a threshold B
, I want to find the smallest C
so that:
C > B
C = A[1] * k[1] + A[2] * k[2] + ... + A[n] * k[n]
,k[i]
are integers >= 0
As an example if A = { 6, 11, 16 }
then the values we can obtain are: { 0, 6, 11, 12, 16, 17, 18, 22, 23, 24, 27, 28, 29, 30, 32 ... }
so if B = 14
then C
would be 16
, B = 22
=> C = 23
, B = 18
=> C = 22
This problem was given these constraints: 2 < n < 5000
0 < A[i] < 50000
and 1 < B < 10^9
( this is why I got stuck ). Also you had to calculate for an array B
of size < 1000
an array C (but this may not matter). And the algorithm should run in under 0.3 sec in C++.
An algorithm like the one described here solves it but it is not fast enough: https://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
I calculate table until B + Amin because Amin * k <= B <= Amin * ( k + 1 ) <= B + Amin
Here's the algorithm (in pseudo C++):
int n, A[n], B;
int Amin; // smallest number from A
// table[i] will tell us if it is possible or not to obtain the number i
bool table[B + Amin];
table[0] = true;
for( int i = 0; i < n; ++i )
{
int x = A[i]; // current number / denomination
for( int j = x; j <= B + Amin; ++j )
if( table[j - x] )
table[j] = true;
}
// now we can do something like this:
int result = B + 1;
while( !table[result] )
++result;
This algorithm has a complexity of O(n*B)
and I'm looking for something that is independent of B
( or maybe has O(log(B))
or O(sqrt(B))
)
Note: if we make the first requirement C >= B
then the problem doesn't change ( just add +1 to B ) and we can ask it like this: If we have specific coins or banknotes ( infinite of them ) and want to purchase something with them, then what is the amount we can pay so that the cashier has to give back minimal change.
Things that I suspect may help:
https://en.wikipedia.org/wiki/Coin_problem
If Greatest Common Divisor ( x, y ) = 1
then anything higher than xy − x − y
can be obtained using x
and y
.
https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
https://en.wikipedia.org/wiki/Subset_sum_problem
Edit: added example and note.