Question 121 of the Hottest Questions 100:
Paste the code first:
class Solution {
public int maxProfit(int[] prices) {
/**
* 遍历数组找到历史价格最低点,再往后遍历,如果出现那一天价格比最低点高,说明有利润(差值)
* 记录下这个利润,继续往后遍历,记录下最大利润,如果最低点后面无元素了,说明
* 这笔交易里没有利润可赚。
*/
//定义最低价格min,初始值为第一天的价格
int min = prices[0];
//定义最大差值diffence
int diffence = 0;
//for循环遍历,若有一天价格小于最低价格,则更新最低价格,若大于则求其利润,并维护最大利润
for(int i = 0;i < prices.length;i++){
if(prices[i] < min){
min = prices[i];
}else if(prices[i] - min > diffence){
diffence = prices[i] - min;
}
}
return diffence;
}
}
Scene reconstruction:
Suppose we don't know the stock price and want to get the maximum profit, then I buy the first day's stock first, wait until the second day if the stock price falls , I quickly sell it and re-buy the second day's stock , if the stock continues to fall on the third day , then I will quickly sell it and buy the stock on the third day.
If the stock goes up on the third day , then I don't sell it immediately, I stay in my hands and wait and see, and then I sell it when the stock rises to the maximum value, and then I can get the maximum profit. The stock continues to rise on the fourth day , which is great, I will wait and see what happens tomorrow. As a result , on the fifth day, the stock fell! It's lower than the stock price on the second day. It's over . Now I regret it. I knew I would sell it on the fourth day. At this time, I have no choice but to sell the second day's stock and buy the first one. Five day stock .
On the sixth day, I took a look at the stock and found that it has risen a lot, much higher than the fourth day ! Now I have to sell the stock quickly, because the trading is not allowed on the seventh day, and if I sell it today, I can get the maximum profit , so I immediately sell the stock and get the maximum profit.
Analysis of ideas:
Through the above real-life restoration, we know that we should buy the stock on the first day first. If the stock on the i-th day is lower than the stock on the first day, then re-buy the stock on that day, and then check whether the stock will rise. If the stock has been showing a downward trend, it means that there will be no profit; if you encounter a rising stock, first write down the profit you can get on that day (the jth day). I don't need the previous profit to show that the maximum profit can be obtained on that day, so I will sell the stock on that day to obtain the maximum profit.