123. Best Time to Buy and Sell Stock III

题目

所给数组的元素prices[i],表示i当天的股票价格,要求求出最大利润,并要求只能买卖两次。

解析

本题目与最初的这道题的区别在于对购买次数提出了限制。原题只要累加每次上升的幅度即可。

WA解法

通过了143/198个测试用例。未通过的边缘用例特点为:在两次盈利之间有一个小小的亏损,在只选取最大和次大的利润累加的思路下,不能比较这两次盈利减去小亏损与次大利润的大小。例如:prices[ ]={6,1,3,2,4,7},a[ ]={-5, 2, -1, 2, 3}

class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;
        if(len == 1) return 0;
        int[] a = new int[len];
        int j = 0;
        for(int i = 1; i < len; i++)
        {
            a[j++] = prices[i] - prices[i-1];
        }
        int max1 = 0;
        int max2 = 0;
        for(int i = 0; i < len-1; i++)
        {
            if(a[i] > max1){
                max2 = max1;
                max1 = a[i];
            }
            else if(a[i] <= max1 && a[i] > max2) max2 = a[i];
        }
        return max1+max2;
    }
}

AC解法

将整个数组以prices[i]划分。分别求i之前最大的涨幅和i之后最大的涨幅。i之前的最大涨幅的求法:遍历数组的过程中,更新 j之前的最小值,计算最小值与prices[j]的差值,同时更新所有j之前的差值中的最大值。i之后最大涨幅的求法同理,从后向前更新最大值,计算prices[j]与最大值的差值,同时更新所有j之后的差值中的最大值。

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

最优解法

最优解法实例
k是可以设定的购买次数,一个循环的含义为寻找一次最佳的购买行为。在一个循环中,maxbuy是max(在当前的盈利情况下购买prices[j]后剩余的资产),profit[j]是max(之前已经买卖过的一次交易的盈利,已买且在j点卖的预计盈利)

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length < 2)  return 0;
        int[] profit = new int[prices.length];
        for(int k=0; k<2; k++) {
            int maxBuy = profit[0] - prices[0];
            for(int i=1; i<prices.length; i++) {
                int tmp = profit[i];
                profit[i] = Math.max(profit[i-1], maxBuy + prices[i]);
                maxBuy = Math.max(maxBuy, tmp - prices[i]);
            }
        }
        return profit[prices.length - 1];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值