Question:The maximum income that can be obtained based on one dollar. The stock price on day I is V [I], 1 <= I <= m
Ideas:
(1) The DP idea is obvious, and direct dynamic planning makes f [I] represent the maximum income obtained on the day I. The formula is as follows:
F [I] = max {f [I-1], F [J] * V [I]/V [J]} (1 <= j <I)
Where f [I-1] means not to sell the stock on day I, F [J] * V [I]/V [J] means to buy from day J, the I-day sale clearly covers all the above situations. The analysis shows that the time complexity of this algorithm is O (n * n) and the space complexity is O (n ).
(2) After analysis, we can find that, in formula F [J] * V [I]/V [J], for the fixed I, V [I] remains unchanged, therefore, we only need to find the maximum value of F [J]/V [J], and then we can find that for each I loop, finding the largest f [J]/V [J] requires only the complexity of O (1). Why? Because the range of J is [1, I-1], and f [J]/V [J] is unchanged, therefore, at the end of each loop, we only need to record the maximum value of F [J]/V [J] (1 <= j <I), so that we can eliminate the cyclic Operation of J, the time complexity is reduced to O (n), and the space complexity is reduced to O (1) because it can be input and processed simultaneously ).
Summary:
So far, through analysis, the time complexity is reduced to O (n), and the space complexity is reduced to O (1). The problem is well solved, not only this question, but many DP problems are analyzed, we can all use the relationship between some variables to simplify the formula or reduce the time-space complexity. Sometimes the same effect can be achieved by converting the thought.
[DP] an ideal income problem [change]