[DP] an ideal income problem [change]

Source: Internet
Author: User
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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.