It explains why the OP solution is placed (the algorithm, in short, must cross the sorted existing elements, save the accumulated sum of the previous existing elements and add the element to the array and sum if it does not exist and exceed the current amount):
The loop checks the order of each element to be formed and sums up the previous elements. He warns us if an item is required that is larger than the current amount. If you think about it, it is very simple! How can we create an element when we have already used all the previous elements, what is the sum?
In contrast to this, how do we know that all intermediate elements can be formed when the sum is larger than the current element? For example, consider n = 7, a = {} :
The function adds {1,2,4...} So we are up to 4 and we know 1,2,3,4 are covered, each can be formed from equal or lower numbers in the array. At any point, m, in the traversal, we know for sure that X0 + X1 ... + Xm make the largest number we can make, call it Y. But we also know that we can make 1,2,3...Xm Therefore, we can make Y-1, Y-2, Y-3...Y-Xm (In this example: Xm = 4; Y = 1+2+4 = 7; Y-1 = 6; Y-2 = 5) QED
source share