Best Time to Buy and Sell Stock II解題

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

<code>Input: [7,1,5,3,6,4]Output: 7Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.            Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3./<code>

Example 2:

<code>Input: [1,2,3,4,5]Output: 4Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.            Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are            engaging multiple transactions at the same time. You must sell before buying again./<code>

Example 3:

<code>Input: [7,6,4,3,1]Output: 0Explanation: In this case, no transaction is done, i.e. max profit = 0./<code>

題目大概意思就是,股票的價格變化如數組中所示,可以多次交易,找出最大利潤,比如說7,1,5,3,6,4,可以1買入5賣出,3買入6賣出,利潤為4+3=7。

這題如何思考,乍一看沒有頭緒,這題我們採用動態規劃的思想來解決,我們用T來表示最大利潤

T(7,1,5,3,6,4) = Max{ T(7,1,5,3,6) , 4到能賺錢的地方比如3或者1 + T(7,1,5)}

所以貼出代碼:

<code>    public static int maxProfit(int[] prices) {                if(prices.length == 0) return 0;        int[] maxProfits = new int[prices.length];        int curMaxProfit = 0;        for (int i = 1; i < prices.length; i++) {            for (int j = i - 1; j >= 0; j--) {                if(prices[i] > prices[j]) {                    curMaxProfit = Math.max(curMaxProfit, prices[i] - prices[j] + (j > 0 ? maxProfits[j - 1] : 0));                }            }            maxProfits[i] = Math.max(maxProfits[i - 1], curMaxProfit);        }        return maxProfits[prices.length - 1];    }/<code>


分享到:


相關文章: