[LeetCode]Best Time to Buy and Sell Stock III

来源:互联网 发布:多益网络 训练营 编辑:程序博客网 时间:2024/05/22 09:42

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


本题难度Hard。

DP

【题意】
最多可以进行两次交易,求最大利润。

【复杂度】
时间 O(N) 空间 O(N)

【思路】
我们仍然用反推法来得到算法。有以下几种可能:

这里写图片描述

可以看出,两次交易的分隔毫无规律,实际上也就意味着求两次交易的最大利润是用遍历的办法找出来的。我们利用DP的方法,分别利用两个DP数组fg

这里写图片描述

然后对所有的i遍历求出最大的f[i]+g[i]就是我们要的答案。

【附】
第9行与第10行、第13行与第14行是可以上下交换的。

【代码】

public class Solution {    public int maxProfit(int[] prices) {        //require        int size=prices.length;        if(size<1)return 0;        int[] f=new int[size],g=new int[size];        //invariant        for(int i=1,valley=prices[0];i<size;i++){            valley=Math.min(valley,prices[i]);            f[i]=Math.max(f[i-1],prices[i]-valley);        }        for(int i=size-2,peak=prices[size-1];i>=0;i--){            peak=Math.max(peak,prices[i]);            g[i]=Math.max(g[i+1],peak-prices[i]);        }        int maxProfit=0;        for(int i=0;i<size;i++)            maxProfit=Math.max(maxProfit,f[i]+g[i]);        //ensure        return maxProfit;    }}
0 0
原创粉丝点击