I need an algorithm for checking if an array can be divided into 2
, or in general, any number of subarrays (need not be contiguous) such that the sum of all the elements of the array does not exceed a certain number. I believe that it basically has to do something with Dynamic Programming. Here's my code in Python:
def func(array, pile1, pile2, memo={}):
if len(array) == 1:
return (array[0] <= pile1 or array[0] <= pile2)
elif sum(array) <= pile1 or sum(array) <= pile2:
return True
elif max(array) > max(pile1, pile2):
return False
elif sum(array) > pile1 + pile2:
return False
elif (array, pile1, pile2) in memo:
return memo[(array, pile1, pile2)]
elif (array, pile2, pile1) in memo:
return memo[(array, pile2, pile1)]
else:
item = array[-1]
array = array[:-1]
pos1 = func(array, pile1-item, pile2, memo) if pile1-item >= 0 else False
pos2 = func(array, pile1, pile2-item, memo) if pile2-item >= 0 else False
memo[(array, pile1, pile2)] = pos1 or pos2
return memo[(array, pile1, pile2)]
The two pile
s originally contain the maximum.
I searched on the web and found no such solution. Could you please help me with this?
Thanks.