An optimal set of moves will always involve making some number of vertical cuts X and some number of horizontal cuts Y. The order is irrelevant so say that the vertical cuts are made first, and that they are made on the X tallest buildings. The number of horizontal cuts still required will be the height of the tallest remaining building. Sort the buildings decreasing by height (assume for convenience that there is at least one building of height 0) and the answer is equal to min(i+H[i]).