I have a assignment for one of my algorithms class that requires us to create an algorithm that takes an array of positive integer values and splits them into 3 separate groups with highest sum of the 3 groups being as low as possible.
i.e: input: [5,3,3,2,2,2,1] output: 6. The groups would be [[5,1],[3,3],[2,2,2]] where the sum of each group is 6.
The goal of the algorithm is to minimize that maximum sum value, the other 2 sums do not matter.
I have written an algorithm that achieves this goal, however it is incredibly slow. The assignment requires the algorithm to run in O((l^2)(n^3)) time, however I believe this runs in O(3^n) time.
The algorithm starts by calculating the sum of the entire array and dividing by 3 to find the average group size if they were able to divide perfectly. The algorithm then tries to put all values into the groups with the average being the cap for each group. If this does not work, then it will try again after adding 1 to the cap.
def works(array, n, a, b, c):
if n < 0:
return True
aworks = False
bworks = False
cworks = False
if a-array[n]>= 0:
aworks = works(array,n-1,a-array[n],b,c)
if b-array[n]>= 0 and b!=a:
bworks = works(array,n-1,a,b-array[n],c)
if c-array[n]>= 0 and c!=a and c!=b:
cworks = works(array,n-1,a,b,c-array[n])
return aworks or bworks or cworks
def minimum_allowable_attendance_for_long_weekend(input_file_path, output_file_path):
# Read data from input file into an array
total = sum(array)
maximum = max(array)
first = int(max(maximum, math.ceil(total/3)))
answer = 0
for target in range(first, total):
if works(array,len(array)-1,target,target,target):
answer = target
break
# Print answer
If there is a way to improve the algorithm, any help would be greatly appreciated