LeetCode——121. Best Time to Buy and Sell Stock

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值