Leetcode 121. best time to Buy and Sell Stock

Source: Internet
Author: User

Last night and classmates to do the game, randomly picked the problem. My idea.

The first thing that comes to mind is that the first number is traversed, and then a maximum number is found from the back of the number, which is, of course, the time complexity of the Loop loop O (N2).

The method is feasible, but time does not pass when the data becomes very large. And then think

For example, there is already a benefit, then how to produce a bigger profit, the factor is that my input price is lower, or the bid is higher. Both can exist at the same time.

So we might as well think, when we walk through the first number is not the next time to traverse from the second number, then the third, fourth, but really need to do this?

In fact, if the second number itself is larger than the first number, then we do not have to go through it all over again, because you have the same price at the back, expensive ah, the benefits are small. Will not generate much more revenue.

So my second idea is that I record the current price, if I find a smaller number than it to update it, if not smaller than it is of course the calculation proceeds ah.

Here's a little bit of how I came up with the benefits of updating it instead of counting the number after it was smaller. The reason is the same, because your bid is the same, the price is expensive ah, the benefits are small.

Like, I'm 2,3,1,9 now.

I'm 2. When I meet 1, I don't need to calculate 1 and 2 gains and then calculate the gains from 9 and 2. I'll just calculate the 1 and 9 benefits.

So I can find a way to go through one of the best returns. That's a lot of talk.

Leetcode 121. best time to Buy and Sell Stock

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.