Equilibrium index of an array of large numbers, how to prevent overflow?

后端 未结 2 1056
独厮守ぢ
独厮守ぢ 2021-01-29 13:23

Problem statement:
An equilibrium index of an array is an index into the array such that the sum of elements at lower indices is equal to the sum o

2条回答
  •  深忆病人
    2021-01-29 13:39

    Yes it is possible. Notice that if data[0] < data[len - 1], then data[1] shall belong to the "left" part; similarly if data[0] > data[len-1] then data[len-2] belongs to the "right" part. This observation allows an inductive proof of correctness of the following algorithm:

    left_weight = 0; right_weight = 0
    left_index = 0; right_index = 0
    
    while left_index < right_index
        if left_weight < right_weight
            left_weight += data[left_index++];
        else
            right_weight += data[--right_index]
    

    Still there is an accumulation, but it is easy to deal with by keeping track of imbalance and a boolean indicator of which side is heavier:

    while left_index < right_index
        if heavier_side == right
            weight = data[left_index++]
        else
            weight = data[--right_index]
    
        if weight < imbalance
            imbalance = imbalance - weight
        else
            heavier_side = !heavier_side
            imbalance = weight - imbalance
    

    At least for unsigned data there is no possibility of overflow. Some tinkering might be required for signed values.

提交回复
热议问题