121. Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
解题思路
题目要求获得最大的利润,我们总是希望在最便宜的时候买入,在最贵的时候卖出,退而求其次,在最贵的时候卖出或者最便宜的时候买入二者达到其一。如果像上面这么考虑这个问题就很容易陷入死局,例如[7,6,3,6,1,2],显然最大利润为3。
这其实是一道动态规划的问题。从开始遍历,遍历每个节点之后标记出“最小价格”和“最大利润”。“最小价格” = 当前节点值 与 当前“最小价格”中较小的一个,“最大利润” = 当前节点值和“最小价格只差” 与 当前“最大利润”的较大的一个。这样避免了陷入单一追求最值的解法,在追求满足最小价格的同时保存当前的最好的结果。
代码如下:
class Solution {
public:
int maxProfit(vector<int> &prices) {
int maxprofit = 0;
int minprice = INT_MAX;
for(int i = 0; i < prices.size(); i++) {
minprice = min(minprice, prices[i]);
maxprofit = max(maxprofit, prices[i] - minprice);
}
return maxprofit;
}
};