121. Best Time to Buy and Sell Stock

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

給定一個數(shù)組,其中數(shù)組的第 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.

分析

該題與 子數(shù)組的最大和 相似 https://leetcode.com/problems/maximum-subarray/ ,其解答參見 http://www.itdecent.cn/p/98676b3baf2c

  • 子數(shù)組的最大和 是求 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])
  • 所以可以將 子數(shù)組的最大和 中的nums[i] 替代為 nums[i+1] - nums[i]

maxhere 記錄的是當(dāng)前購買和賣出的利潤,如果利潤小于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;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容