I encounter a problem to let you drop two elements in an array to make the three part\'s sum equal.
Ex:
1 2 4 3 5 2 1
After I drop the 4 and 5, it becomes
Assuming that first and last element can't be dropped and all elements are >0
:
Set a variable sumleft
to value of first element, sumright
to value of last element. You also need index variables to remember which elements from left and right were already added to the sums.
If sumleft == sumright
, test if next elements from left and right can be dropped to fulfill requirement. If so -> done. If not take next elements from left and right and add it to the respective sum variable. Back to 1.
If sumleft < sumright
, add next value from the left to sumleft
. Back to 1.
sumleft > sumright
, add next value from the right to sumright
. Back to 1.If all elements were consumed, there is no solution.
Edit: Testing if requirement is fulfilled when sumleft == sumright
can be done by initially summing up all elements (also needs only O(n)
) and checking if this sum minus the elements to drop is equal sumleft * 3
.