leetcode_Best Time to Buy and Sell Stock III

来源:互联网 发布:macbook air卸载软件 编辑:程序博客网 时间:2024/06/03 17:42

描述:

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.

思路:

给两次交易机会,让求最大的利润,先从左向右求到当前节点的最大利润并将其存储到一个数组profit1[ ]中,然后从右向左求到当前节点的最大利润并将其存储到一个数组profit2[ ]中,然后从前向后遍历求到某个节点时其左右部分的利润相加,然后和当前最大利润相比从而得出最大利润。

代码:

public int maxProfit(int[] prices) {        if(prices==null)            return 0;        int len=prices.length;        if(len==0)            return 0;        int maxProfit=0;        int tempPre=prices[0];        int tempCur=0;        prices[0]=0;        for(int i=1;i<len;i++)        {        tempCur=prices[i];        prices[i]=prices[i]-tempPre;        tempPre=tempCur;        }maxProfit=getMaxProfit(prices);        return maxProfit;    }    public int getMaxProfit(int profit[])    {        int len=profit.length;        int profitFromEnd[]=new int[len];        for(int i=0;i<len;i++)            profitFromEnd[i]=profit[i];        for(int i=1;i<len;i++)        {            if(profit[i-1]>0)                profit[i]=profit[i-1]+profit[i];        }        for(int i=len-2;i>=0;i--)        {            if(profitFromEnd[i+1]>0)                profitFromEnd[i]=profitFromEnd[i]+profitFromEnd[i+1];        }        int max=profit[0];        for(int i=1;i<len;i++)        {            if(max<profit[i])                max=profit[i];            profit[i]=max;        }        max=profitFromEnd[len-1];        for(int i=len-2;i>=0;i--)        {            if(max<profitFromEnd[i])                max=profitFromEnd[i];            profitFromEnd[i]=max;        }        int maxProfit=0;        int tempMaxProfit=0;        int count=len-1;        for(int i=0;i<count;i++)        {            tempMaxProfit=profit[i]+profitFromEnd[i+1];            if(maxProfit<tempMaxProfit)                maxProfit=tempMaxProfit;        }        return maxProfit;    }


0 0
原创粉丝点击