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

前端 未结 3 2084
迷失自我
迷失自我 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:44

    The results below are more a "brute" approach, should work for negative numbers as well. Also a version where we can remove any 2 items and split by any index is added. although it's just a pseudo code.

    if the array is split by those items we take out...

    var count = a.Length (a is input)
    
    // we need:
    for i=0; i 0) sumLeft[i] += sumleft[i-1]
    sumRight[cnt-1-i] = a[i]; if (i > 0) sumRight[cnt-1-i] += sumRight[cnt-1+1-i]
    
    // calc:
    for i=1; ii; j--;
    if (sumLeft[i-1] == sumRight[j+1-1] == sum - a[i] - a[j] - sumLeft[i-1] - sumRight[j-1]) return true;
    
    otherwise return false aft cycle
    

    if we can take out any 2 items and split in any position:

    for i=0; i

提交回复
热议问题