121. Best Time to Buy and Sell S

2020-04-05  本文已影响0人  默写年华Antifragile

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

给定一个数组,其中数组的第 i 个元素表示第 i 天的股票价格,你可以选择在其中一天买股票,然后再后面的某一天卖掉股票,求最大收益。(股票必须要先买才能卖)这里只能买一次,也只能卖一次
------
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.

分析

该题与 子数组的最大和 相似 https://leetcode.com/problems/maximum-subarray/ ,其解答参见 https://www.jianshu.com/p/98676b3baf2c

maxhere 记录的是当前购买和卖出的利润,如果利润小于0,就要重新购买股票,即将maxhere置0;
同时用一个maxsofar记录每次购买和卖出的利润,取其最大值

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int maxhere = 0, maxsofar = 0;
        for (int i=1; i<prices.size(); ++i)
        {
            maxhere = (maxhere + prices[i]-prices[i-1])> 0?(maxhere + prices[i]-prices[i-1]):0;
            maxsofar = maxhere > maxsofar ? maxhere : maxsofar;
        }
        return maxsofar;
    }
};
上一篇下一篇

猜你喜欢

热点阅读