Suppose you are a freelance programmer who needs to decide which job to take each week. The set of possible jobs is divided into low-stress and high-stress ones. The basic question each week is whether to take on a low-stress job or a high-stress job. If you select a low-stress job in week i, you get a revenue of f > 0. If you select a high-stress job, you get a revenue of h > 0. The catch, however, is that in order to take on a high-stress job in week i, it is required that you take no job (of either type) in week i-1. You need a full week of prep time to get ready for the crushing stress level. On the other hand, you can take a low-stress job in week i even if you have done a job (of either type) in week i-1. Given a sequence of n weeks, a valid plan is specified by a choice of low-stress, high-stress, or none for each of the n weeks, with the property that if high-stress is chosen for week i > 1, then none has to be chosen for week i-1. It is okay to choose a high-stress job in week 1. The value of the plan is the sum of the revenue you get in each week: f if you choose low-stress in week i, h if you choose high-stress, and 0 if you choose none. The problem is to find a plan of maximum value given n > 0 and f, h, ..., hn > 0. For example, suppose n = 4 and the values of f and h are given by the following table:
week | 1 | 2 | 3 | 4 |
-------|---|---|---|---|
f | 0 | 0 | 10| 10|
h | 50| 0 | 0 | 0 |
Then the plan of maximum value would be to choose no job in week 1, a high-stress job in week 2, and low-stress jobs in weeks 3 and 4. The value of this plan would be 0 + 50 + 10 + 10 = 70.
a) Does the following algorithm correctly solve this problem? Justify your answer.
```
for i = 1 to n do
if hi+1 > hi then
Output choose no job in week i
Output choose a high-stress job in week i+1
Continue with iteration i+2
else
Output choose a low-stress job in week i
Continue with iteration i+1
```
b) Give an algorithm that outputs the value of the optimal plan. Your algorithm should run in time O(n). Prove the correctness of your algorithm and analyze its running time.