121. Best Time to Buy and Sell Stock

Posted qiulinzhang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了121. Best Time to Buy and Sell Stock相关的知识,希望对你有一定的参考价值。

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

  • 子数组的最大和 是求 nums[i] + .... + nums[j] 的最大值
  • 而这里买股票和卖股票是求 num[j] - num[i] 的最大值,而
    nums[j] - nums[i] = (nums[j] - nums[j-1]) + (nums[j-1] - nums[j-2]) + ..... + (nums[i+1] - nums[i])
  • 所以可以将 子数组的最大和 中的nums[i] 替代为 nums[i+1] - nums[i]

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;
    }
};

以上是关于121. Best Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stockeasy

121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock