Best Time to Buy and Sell Stock III

来源:互联网 发布:windows计划任务日志 编辑:程序博客网 时间:2024/05/17 14:15

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).

与前两题相比 更改了要求 只能进行一次或者两次操作 故可以将其分为左右两部分 各视为一次操作 当左边或右边为0时  就相当于操作一次  然后分别求得两半边的profit最大值 进行相加得到总值  最后进行一次比较即可得出结果  具体写时 左右各建一个数组lpro  rpro 分别存储profit值 注意的是 左右两边的数组值只要一次遍历即可得到 因为前后有关联 lpro[i]=max(lpro[i-1],pricrs[i]-min); 右边的 rpro[i]=max(rpro[i+1],max-prices[i]); 代码如下;

public class Solution {    public int maxProfit(int[] prices) {       if(prices.length<=1)return 0;int[] lpro=new int[prices.length];        int[] rpro=new int[prices.length];        int min=prices[0];        lpro[0]=0;        for(int i=1;i<prices.length;i++){if(min>prices[i])min=prices[i];lpro[i]=Math.max(lpro[i-1],prices[i]-min);}        rpro[prices.length-1]=0;        int max=prices[prices.length-1];        for(int i=prices.length-2;i>=0;i--){        if(max<prices[i])max=prices[i];        rpro[i]=Math.max(rpro[i+1], max-prices[i]);        }        int res=0;        for(int i=0;i<prices.length;i++){        if(lpro[i]+rpro[i]>res)res=lpro[i]+rpro[i];        }        return res;    }}

 

0 0