Drop two elements to split the array to three part evenly in O(n)

前端 未结 3 2031
迷失自我
迷失自我 2021-02-07 19:07

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          


        
3条回答
  •  清歌不尽
    2021-02-07 19:58

    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.

    1. 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.

    2. If sumleft < sumright, add next value from the left to sumleft. Back to 1.

    3. If 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.

提交回复
热议问题