123. Best Time to Buy and Sell Stock III

来源:互联网 发布:网络流行语mgt什么意思 编辑:程序博客网 时间:2024/05/22 05:10

题目:

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.
只允许交易两次,找出最大利润。

动态规划

  • 定义:int[][] local = new int[length][3]; local[i][j]表示第i天进行j次交易后最优解(必须包含当前天的最优解)。
    int[][] global = new int[length][3]; global[i][j]表示表示第i天进行j次交易后最优解。

  • 初始状态:local 和global 都为0.

  • 状态转移:
    local[i][j]=Math.max(global[i-1][j-1]+Math.max(diff,0),local[i-1][j]+diff);
    其中global[i-1][j-1]+Math.max(diff,0)表示前一天少一次交易的最优解,加上今天交易一次的大于0差值、local[i-1][j]+diff表示前一天进行j次交易的最优解加上今天的差值.
    global[i][j]=Math.max(local[i][j],global[i-1][j]);
    其中local[i][j]表示加上今天差值的最优解,若比global[i-1][j]大则global[i][j]=local[i-1][j],反之同理。

public int maxProfit(int[] prices) {        if(prices==null || prices.length==0)            return 0;        int length=prices.length;        int[][] local = new int[length][3];        int[][] global = new int[length][3];        int diff = 0;        for(int i=1;i<prices.length;++i)        {            diff=prices[i]-prices[i-1];            for(int j=1;j<3;++j){//              local[i][j]:前一天进行j-1次交易全局变量与前一天进行j次交易的局部最优中找最大值。即选择今天交易或者不交易。                local[i][j]=Math.max(global[i-1][j-1]+Math.max(diff,0),local[i-1][j]+diff);                global[i][j]=Math.max(local[i][j],global[i-1][j]);            }        }        return global[length-1][2];    }
原创粉丝点击