I think you can do this simply by scanning in each direction, tracking the cumulative value (in that direction) in the current array and the desired output array, and pushing the values forward as needed:
scan from the left looking for first cell where cumulative value > cumulative value in desired output while that holds move 1 from that cell to the next cell to the right scan from the right looking for first cell where cumulative value > cumulative value in desired output while that holds move 1 from that cell to the next cell to the left
As an example, follow these steps:
FWD: [0,0,8,0,0] [0,0,7,1,0] [0,0,6,2,0] [0,0,6,1,1] [0,0 , 6.0.2]
REV: [0,1,5,0,2] [0,2,4,0,2] [1,1,4,0,2] [2,0,4,0,2]
Ian mercer
source share