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

思路一
  1. 第一次从左到右,得到从开始到第 i 天,所能获得的最大收益。
  2. 第二次从右到左,得到从第 i 天到最后一天,所能获得的最大收益。
  3. 最后,对于任意的 i (0 <= i < size),它把数组分成两部分,这两部分的最大收益之和就是最终的收益。找出其中最大的那个。
代码
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length < 2)
            return 0;

        int maxProfit = 0;
        //保存从开始到第i天,所能获得的最大收益
        int[] maxProfitTo = new int[prices.length];
        int minPrice = prices[0];
        for(int i = 1;i < prices.length;i++){
            maxProfitTo[i] = Math.max(maxProfitTo[i -1],prices[i] - minPrice);
            minPrice = Math.min(minPrice,prices[i]);
        }
        //保存从第i天到最后一天所能获得的最大收益
        int[] maxProfitFrom = new int[prices.length];
        int maxPrice = prices[prices.length - 1];
        for(int i = prices.length - 2;i >= 0;i--){
            maxProfitFrom[i] = Math.max(maxProfitFrom[i + 1],maxPrice - prices[i]);
            maxPrice = Math.max(maxPrice,prices[i]);
        }
        //最后对于任意的i(0<=i<length),他把数组分成两部分,这两部分最大的收益之和就是最终的收益。
        for(int i = 0;i < prices.length;i++){
            maxProfit = Math.max(maxProfit,maxProfitTo[i] + maxProfitFrom[i]);
        }
        return maxProfit;
    }
}
结果及分析

时间复杂度为O(n),空间复杂度为O(n);

思路二

跟思路一差不多,把数组分为两部分,相当于两个时期,在每个时期内进行一次交易获得的最大值,这个以前做过,比较好实现。分法有很多种,遍历一遍就好了。

代码
public class Solution {
    public int maxProfit(int[] prices) {
        //把股价分为两部分,[0-i]为一次最大收益,[i-len]为一次最大收益;
        //一次交易的最大收益,这个我们已经会求了;
        if(prices == null || prices.length < 2)
            return 0;
        int maxProfit = 0;

        for(int mid = 1;mid < prices.length;mid++){
            int firProfit = 0,secProfit = 0;
            int firLow = prices[0],secLow = prices[mid];
            for(int firSell = 0;firSell <= mid;firSell++){
                firProfit = Math.max(firProfit,prices[firSell] - firLow);
                firLow = Math.min(firLow,prices[firSell]);
            }
            secLow = prices[mid];
            for(int secSell = mid;secSell < prices.length;secSell++){
                secProfit = Math.max(secProfit,prices[secSell] - secLow);
                secLow = Math.min(secLow,prices[secSell]);
            }
            maxProfit = Math.max(maxProfit,firProfit + secProfit);
        }
        return maxProfit;
    }
}
结果及分析

超时了,时间复杂度为O(n^2),空间复杂度为O(1);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值