def knapSack(A,L,R,K,N,Sum):
if(K==0):
if((L>=Sum)or(R<=Sum)):
return 1
else:
return 0
if((N==0)and(K!=0)):
return 0
else:
return knapSack(A,L,R,K,N-1,Sum)+knapSack(A,L,R,K-1,N-1,Sum:=Sum+A[N-1])
A = [2,4,10,25]
K = 2
L = 3
R = 13
Sum=0
n = len(A)
print(knapSack(A,L,R,K,n,Sum))
The Output Of this Code is: 4
Explanation:
25+10 =35
25+4 = 29
25+2 = 27
10+4 = 14
These Sums satisfies the given condition if((L>=Sum)or(R<=Sum)) where L=3 R=13
K is the size of the subset. Here, K = 2
When K = 3
A = [2,4,10,25]
K = 3
L = 3
R = 13
Sum = 0
n = len(A)
print(knapSack(A,L,R,K,n,Sum))
The Output Of this Code when K = 3 is: 4
Explanation:
4+10+25 = 39
2+4+25 = 31
2+10+25 = 37
2+4+10 = 16
These Sums satisfies the given condition if((L>=Sum)or(R<=Sum)) where L=3 R=13
Is There a way to solve this problem in Dynamic Programming or any other better way?
Here is a dynamic programming algorithm you can use. The algorithm will be used to generate all subsets of size
K. This algorithm uses one element ofAone after another to build subsets.STEPS
Initialize a
listwith theempty set. Also initialize aglobal_counterwhich will be used to keep count of subsets of sizeKthat satisfies the given condition.Iterate the elements of
A. For eachA[i], do the following;i. Create new subsets by appending
A[i]to all the current elements in thelist(Notice thatlistis currently containing the subsets created usingA[0] to A[i-1]).ii. For each of the new subsets created in
2.iusingA[i], letsumbe the sum of the elements in the subset, andcountbe the number of elements in the subset. Ifcount == K AND (sum <= L OR sum >= R)then increment theglobal_counter. Ifcount < K, insert the newly created subset into thelist.Return the
global_counter.NB: Instead of storing every intermediate subset as a list of elements, we will use
(sum, count)pairs to represent subsets. Wheresumrepresent the sum of elements in the subset, whilecountrepresent the number of elements in the subset. This way we can reduce the memory required to store all the created subsets and the time required to compute thesumandcounteach time a subset is created, sincesumandcountof the a newly created subset can be updated in constant time from the its previous subset.Time Complexity: O(2^N) - Notice that at worst case,
K = N