[LeetCode]Best Time to Buy and Sell Stock III

股票买卖最佳策略
本文介绍了一种算法,用于计算给定股票价格数组中通过至多两次买卖交易所能获得的最大利润。该算法采用动态规划方法,首先向前遍历计算第一次买入卖出的最大收益,再向后遍历计算第二次买卖的最大收益,并最终确定整体的最大利润。

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值