123. Best Time to Buy and Sell Stock III(dp)

来源:互联网 发布:织梦小说源码 编辑:程序博客网 时间:2024/06/05 14:54

题目:

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

同上,可以但是只能买两次

设状态f(i)表示区间[0,i-1]上的最大利润,设置状态g(i),表示区间[i,n-1]上最大利润。则最大利润为max{f(i)+g(i)};

public class Solution {    public int maxProfit(int[] prices) {    if(prices == null || prices.length<2)return 0;    int max = 0;    int n = prices.length;    int[] l = new int[n];    int[] r = new int[n];    int min = prices[0];    for(int i=1;i<n;i++)    {    min = Math.min(prices[i], min);    l[i]=Math.max(prices[i]-min, l[i-1]);    }    int maxx = prices[n-1];    for(int i=n-2;i>=0;i--)    {    maxx= Math.max(prices[i], maxx);    r[i]=Math.max(maxx-prices[i], r[i+1]);    }        for(int i=0;i<n;i++)    {    max = Math.max(max, r[i]+l[i]);    }        return max;    }}


0 0
原创粉丝点击