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.

我們可以用兩種方法解決這個(gè)問題
第一種方法,首先,為了更好地理解動(dòng)態(tài)規(guī)劃的過(guò)程,我們開多個(gè)數(shù)組以便更好的理解

minPrice[i]: 到第i天為止的最低價(jià)格
maxProfit[i]: 到第i天能獲得的最大收益
maxProfit[i] = max(maxProfit[i-1], prices[i] - minPrice[i-1])

此時(shí),時(shí)間復(fù)雜度為O(n),空間復(fù)雜度為O(n),我們可以通過(guò)將數(shù)組變?yōu)樽兞渴箍臻g復(fù)雜度變?yōu)镺(1)。

Solution

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        if(n < 1) {return 0;}
        
        //int[] minPrice = new int[prices.length];
        //int[] maxProfit = new int[prices.length];
        //minPrice[0] = prices[0];
        //maxProfit[0] = 0;
        int min = prices[0];
        int max = 0;
        for (int i = 1; i < prices.length; i++){
            //minPrice[i] = Math.min(minPrice[i-1], prices[i]);
            //maxProfit[i] = Math.max(maxProfit[i-1], prices[i] - minPrice[i-1]);
            min = Math.min(min, prices[i]);
            max = Math.max(max, prices[i] - min);
        }
        return max;
        //return maxProfit[n-1];
    }
}

第二種方法,可以將該問題轉(zhuǎn)換為max subarray問題
從受益的角度出發(fā),狀態(tài)轉(zhuǎn)移矩陣為P[i] = max(gain[i], P[i-1] + gain[i])
如果P[i-1]為負(fù),則沒有必要從前面開始。

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int sum = 0;
        int flag = 0;
        for (int i = 1; i < n; i++){
            flag = Math.max(0, flag + prices[i] - prices[i-1]);
            sum = Math.max(flag, sum);
        }
        return sum;
        
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。