A contiguous subsequence of a list S is a subsequence made up of consecutive elements of S. For instance, if S is 5, 15, 30, 10, 5, 40, 10, then 15, 30, 10 is a contiguous subsequence but 5, 15, 40 is not. Give a linear-time algorithm for the following task: Input: A list of numbers, a1, a2, . . . , an. Output: The contiguous subsequence of maximum sum (a subsequence of length zero has sum zero). For the preceding example, the answer would be 10, 5, 40, 10, with a sum of 55. (Hint: For each j {1, 2, . . . , n}, consider contiguous subsequences ending exactly at position j.)
Read moreTextbook Solutions for Algorithms
Question
You are going on a long trip. You start on the road at mile post 0. Along the way there are \(n\) hotels, at mile posts \(a_{1}<a_{2}<\cdots<a_{n}\), where each \(a_{i}\) is measured from the starting point. The only places you are allowed to stop are at these hotels, but you can choose which of the hotels you stop at. You must stop at the final hotel (at distance \(a_{n}\)), which is your destination.
You'd ideally like to travel 200 miles a day, but this may not be possible (depending on the spacing of the hotels). If you travel \(x\) miles during a day, the penalty for that day is \((200-x)^{2}\). You want to plan your trip so as to minimize the total penalty, that is, the sum, over all travel days, of the daily penalties. Give an efficient algorithm that determines the optimal sequence of hotels at which to stop.
Solution
Step 1 of 3
Suppose the minimum penalty incurred by a sequence of stops that starts at milepost 0 and ends at mile post \(a_{k}\) is \(C(k)\).
Our aim in this problem is to find sequence such that
\(C(k)=\min \left(200-\left(a_{k}-a_{j}\right)\right)^{2}+C(j)\) where \(0<j<k-1\)
full solution