Base case: dp[0]=0. Each j < i contributes a line fj(x)=−2h[j]x+(h[j]2+dp[j]). Starting line L0 from j=0: slope =−2⋅0=0, intercept =02+0=0, so L0:y=0. The horizontal axis coincides with L0 for this base case.
Step 2 / 9
Query x=h[1]=2. Only L0 is in the envelope so far, so minj<1fj(2)=L0(2)=0. Therefore dp[1]=h[1]2+0=4+0=4.
Step 3 / 9
Insert L1 for j=1: slope =−2⋅h[1]=−4, intercept =h[1]2+dp[1]=4+4=8. L1:y=−4x+8. Note L1(2)=0, exactly where L0 stands: L1 joins the envelope from x=2 onward.
Step 4 / 9
Query x=h[2]=3. L0(3)=0 and L1(3)=−4⋅3+8=−4. The minimum is L1(3)=−4. Therefore dp[2]=h[2]2+(−4)=9−4=5.
Step 5 / 9
Insert L2 for j=2: slope =−2⋅h[2]=−6, intercept =h[2]2+dp[2]=9+5=14. L2:y=−6x+14. Check: L2(3)=−4=L1(3). The new line touches the envelope at the next query point and becomes the winner for x≥3.
Step 6 / 9
Query x=h[3]=4. L0(4)=0, L1(4)=−16+8=−8, L2(4)=−24+14=−10. The minimum is L2(4)=−10. L2 now dominates the envelope near the query. dp[3]=16+(−10)=6.
Step 7 / 9
Insert L3 for j=3: slope =−8, intercept =16+6=22. L3:y=−8x+22. Again L3(4)=−10=L2(4): the new line joins at the next query. Monotone slopes mean no line ever gets removed from the envelope in this input.
Step 8 / 9
Query x=h[4]=5. L0(5)=0, L1(5)=−12, L2(5)=−16, L3(5)=−18. The minimum is L3(5)=−18. dp[4]=25+(−18)=7, the final answer.
Step 9 / 9
Done. dp=[0,4,5,6,7]. The lower envelope (highlighted) consists of four pieces: L0 on [0,2], L1 on [2,3], L2 on [3,4], L3 on [4,+∞). Each CHT query at x=h[i] drops to the current envelope in O(logn) total, so the DP runs in O(nlogn) instead of O(n2). The classic application: Batch Scheduling, Train Plans, and CEOI 2004 Two-Sawmills.