-1

Given a set size $n$ consisting of elements from $1 \rightarrow n$, choose $k$ elements from the set such that their summand equals $S$, if possible

For ex: $n = 5$ (i.e the choices $\{1,2,3,4,5\}$), $k = 3$ and $S=9$ then elements chosen are $1,3$ and $5$

So is there a general formula or a general approach on how to choose such elements? because n and k can be really large.

You can give me the gist or go ahead.

gowrath
  • 3,573
  • 13
  • 31
  • This is the typical problem which can be solved with a greedy algorithm. – Crostul Aug 28 '16 at 11:02
  • why a negative vote? What have I done wrong? – user42638 Aug 28 '16 at 11:03
  • @Crostul can you please elaborate? – user42638 Aug 28 '16 at 11:03
  • Well, you start with an empty list $L$, and the list $N= { 1, \dots , n }$. Pick the largest number from $N$ and put it inside $L$, and repeat this process until the sum of the elements inside $L$ is too big (larger than $S$). When you are at this point, simply remove from $L$ the last element, and put inside $L$ the correct element in such a way that the sum is exactly $S$. – Crostul Aug 28 '16 at 11:08
  • OK, actually this process does not work, since it does not ensure that the final result has exactly $k$ elements. – Crostul Aug 28 '16 at 11:10
  • @user42638 Do the $k$ elements have to be unique? – gowrath Aug 28 '16 at 12:19
  • @Crostul Also you can just choose to continue the algorithm's search if $\vert{L}\vert \neq k$. If you ensure your search is in order, then this will eventually find the desired $L$. – gowrath Aug 28 '16 at 12:21
  • @gowrath yes, they have to be unique. I've got the idea now...I'll post the detailed answer later. – user42638 Aug 28 '16 at 14:04

1 Answers1

0

Well, you can first deduce that $S \in \left[1, \frac{n(n+1)}{2}\right] \subset \mathbb{N}.$ Then for an $S$ in this discrete interval the formula you seek would be the partitions of $S$ into $k$ distinct parts less than or equal to $n$, for which I believe there is no closed form formula, but looking into partitions may get you more information. There may be a generating function for this but I am not positive.

There is discussion of the generation function for partitions of $S$ into just distinct parts here The number of partitions of $n$ into distinct parts equals the number of partitions of $n$ into odd parts but partitions of $S$ into $k$ distinct parts all less than or equal to $n$ would certainly require more work.

Prince M
  • 3,893