With each element in the array we are finding out what all subset sums are possible. Lets take an example 2, 3, 5. If you consider only first element β2β we can achieve only one sum which is 2. If you consider first two elements β2β and β3β we can achieve sums 2, 3, 5(2+3). If you consider first three elements β2β, β3β and β5β we can achieve sums 2, 3, 5(2+3), 7(2+5), 8(3+5), 10(2+3+5).
In the above code, array m is filled with β1β whose sums can be achieved. At the end 'Mβth index of array m is true then sum βMβ can be achieved, otherwise not.(Note: m[0] is true because sum β0β is always achieved)
Initially set all elements to 0 , i.e, m[0β¦10] = 0
what is m?
m[ x ] = 1 if x can be formed by selecting a subset of n and adding them, else it is 0
set m[0] = 1 , You can always make 0 by selecting none.
so now the array looks like 1 0 0 0 0 0 0 0 0 0
Now take one element from n
Take β2β β¦
If for any x , if m[x] == 1 , then this β2β can be added to that value to make a sum of x+2
This statement m[x] = m[x] | m[x-n[i]] does that β¦ if m[x] is already 1 or m[x-n[i]] is 1 , then set m[x] to 1
so now the array looks like 1 0 1 0 0 0 0 0 0 0 0
Take β4β
You can add it to 0 and make 4, or add it to 2 and make 6
so now the array looks like 1 0 1 0 1 0 1 0 0 0 0
Take β5β
0 + 5 = 5
2 + 5 = 7
4 + 5 = 9
6 + 5 = 11( we dont need this ,we need <= 10 )
Finally Array is
1 0 1 0 1 1 1 1 0 1 0
One last point notice for(j=M; j>=a[i]; jβ) , It runs from right to left in array (higher to lower) , This is to avoid reusing the same element twice.