A wide river has n pillars standing out of the water, and their heights may differ. The pillars stand in a straight line from one bank to the other. You want to build a bridge that rests on these pillars. To do that, pick a subset of the pillars and join the tops of consecutive picked pillars into bridge sections. The subset must contain the first pillar and the last pillar.
Building a section between two consecutive picked pillars i and j costs (hi−hj)2, where hi is the height of pillar i. The square keeps the bridge from running steeply uphill or downhill. Every pillar left out of the bridge blocks river traffic and has to be removed. Removing pillar i costs wi. This cost can be negative, because some interested parties are willing to pay you to get certain pillars out of the way. All heights hi and all costs wi are integers.
Find the minimum possible total cost of a bridge that connects the first pillar to the last one.