As amit noted, this algorithm can be understood as an instance of a partition problem. For a simple implementation, take a look at this Python code:
def partition(A): n = len(A) if n == 0: return 0 k, s = max(A), sum(A)/2.0 table = [0 if x else 1 for x in xrange(n*k)] for i in xrange(n): for j in xrange(n*k-1, -1, -1): if table[jA[i]] > table[j]: table[j] = 1 minVal, minIdx = float('+inf'), -1 for j in xrange(int(s)+1): if table[j] and sj < minVal: minVal, minIdx = sj, j return int(2*minVal)
When called with one of the inputs in the question:
partition([10, 50, 60, 65, 90, 100])
He will return 5
, as expected. To fully understand the math behind the solution, check out these examples and click on the Balanced Separation link.
source share