# Finding a non negative combination of integers that adds up to a certain number [duplicate]

I have a set of positive numbers: $${n_1,n_2,...n_k}$$ s.t. $$n_1>n_2>\dots >n_k$$.

I want to find an array of non-negative integers $$c_1,c_2,\dots,c_k$$ such that

$$n_1c_1 + n_2c_2 + \dots + n_kc_k = N$$

for some given number $$N$$.

I have looked into Knapsack and unbounded knapsack, but they don't explicitly look to calculate the coefficients that I'm looking for, they look to maximise the value of items. I'm not sure how to solve this. The subset sum is similar, but we need subsets of multisets here.

Also, is it possible to do this in $$O(n)$$ time?

• Outline: You can definitely make the sum 0. Try adding each of $n_1, \dots, n_k$ to this sum: each of these new values is also a sum you can make, so record it as such. Because all your numbers are positive, each of these sums is also greater than what you started with (0 in this case), so you have not found a way to make any new sums less than 0 -- that means you won't miss anything if you look for the next higher sum you can make, and repeat the process. Nov 3, 2019 at 19:29
• related: same problem where all $c_k$ are restricted to 0 or 1 on stackoverflow: stackoverflow.com/questions/18305843/… time complexity $O(sum * n)$ space complexity $O(sum)$ using dynamic programming where sum is the sum of all $c_k$. see this answer by Толя stackoverflow.com/a/18308020 Maybe one could promote that complexity result to your more general problem? - not sure. Nov 4, 2019 at 9:23
• In general, there may be multiple solutions $(c_k)$ given the same sequence of possible numbers $(n_k)$. The question is: do you want any one solution which happens to fit, a specific solution or all matching solutions? For reference, this combinatorial problem is also a classic special case of the Subset Sum Problem called the Perfect Sum Problem by a few random programming exercise sites on the net (which is the best I could find). Nov 4, 2019 at 9:24