I'm solving a practice problem for algorithm study and looking for the fastest implementation for the problem below.
Given there is a list L
of positive one digit integers of length N, define three points A
, B
, and C
in L
so that the list is divided into three partitions. Note that A < B < C
in terms of indices. The first partition is all elements between A
and B
, the second partition is between B
and C
, and the third partition is all other elements.
Then let h
, i
, and j
be the sum of each partition. I want to find a the minimal value of max([h, i, j]) - min([h, i, j])
in all possible partitioning.
For example, if L = [4, 5, 6, 7, 6, 5, 4]
, then the portioning will be
a = [6, 7]
b = [6, 5]
c = [4, 5, 4] # reminder
# because
h = sum(a) -> 13
i = sum(b) -> 11
j = sum(c) -> 13
# that minimize the difference
max([h, i, j]) - min([h, i, j]) -> 2
The only way I currently came up with is to brute force all possible partitioning so that
current_min = sum(L)
N = len(L)
for A in range(N):
for B in range(A, N):
for C in range(B, N):
sum_1 = sum(L[A:B])
sum_2 = sum(L[B:C])
sum_3 = sum(L[:A]) + sum(L[C:])
sums = [sum_1, sum_2, sum_3]
if max(sums) - min(sums) < current_min:
current_min = max(sums) - min(sums)
But I can see that my solution isn't ideal. Is there any faster way?