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