[LeetCOde][Java] Best Time to Buy and Sell Stock III

來源:互聯網
上載者:User

標籤:leetcode   java   best time to buy and   

題目:

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 at most two transactions.

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

演算法分析:

利用通用的演算法《Best Time to Buy and Sell Stock IV》 將k變為2 就ok 

AC代碼:

<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution{    public int maxProfit(int[] prices)     {        return maxProfit(2,prices);    }    public int maxProfit(int k, int[] prices)     {       if(prices==null || prices.length==0)            return 0;        if(k>prices.length)//k次數大於天數時,轉化為問題《Best Time to Buy and Sell Stock II》--無限次交易的情景         {            if(prices==null)                return 0;            int res=0;            for(int i=0;i<prices.length-1;i++)            {                int degit=prices[i+1]-prices[i];                if(degit>0)                    res+=degit;            }            return res;        }        /*      定義維護量:      global[i][j]:在到達第i天時最多可進行j次交易的最大利潤,此為全域最優      local[i][j]:在到達第i天時最多可進行j次交易並且最後一次交易在最後一天賣出的最大利潤,此為局部最優      定義遞推式:      global[i][j]=max(global[i-1][j],local[i][j]);即第i天沒有交易,和第i天有交易      local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff)  diff=price[i]-price[i-1];       */        int[][] global=new int[prices.length][k+1];        int[][] local=new int[prices.length][k+1];        for(int i=0;i<prices.length-1;i++)        {            int diff=prices[i+1]-prices[i];            for(int j=0;j<=k-1;j++)            {                local[i+1][j+1]=Math.max(global[i][j]+Math.max(diff,0),local[i][j+1]+diff);                global[i+1][j+1]=Math.max(global[i][j+1],local[i+1][j+1]);            }        }        return global[prices.length-1][k];    }}</span>

著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCOde][Java] Best Time to Buy and Sell Stock III

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.