Best Time to Buy and Sell Stock III

题目

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

方法

只能进行两次买入卖出,很自然的想法就是进行二分。

设数组的长度是len, A[0,..,i] ,A[i,...len - 1] 分别计算数组两部分的maxProfit,然后求和。

上述操作需要进行n次,然后返回最大的结果。显然时间复杂度(N^2)。

可以考虑使用空间换时间,从前往后遍历一遍数组,可以获取从0到i的最大maxProfit,将结果放入到数组中,

从后往前遍历一遍数组,可以获取从i到len-1的最大maxProfit,将结果放入到数组中,

遍历一遍,就可以获得结果。

    public int maxProfit(int[] prices) {
    	if (prices == null) {
    		return 0;
    	}
    	int len = prices.length;
    	if (len == 0 || len == 1) {
    		return 0;
    	}
    	
    	int[] maxPre = new int[len];
    	int[] maxPost = new int[len];
    	
    	int min = prices[0];
    	int max = prices[0];
    	int maxPro = 0;
    	maxPre[0] = 0;
    	for (int i = 1; i < len; i++) {
    		if (prices[i] > max) {
    			max = prices[i];
        		int tempMaxPro = max - min;
        		if (tempMaxPro > maxPro) {
        			maxPro = tempMaxPro;
        		}
        		
    		}  else if (prices[i] < min) {
        		min = prices[i];
        		max = prices[i];
        	}
    		maxPre[i] = maxPro;
    	}
    	
    	
    	min = prices[len - 1];
    	max = prices[len - 1];
    	maxPro = 0;
    	maxPost[len - 1] = 0;
    	for (int i = len - 1; i > 0; i--) {
    		if (prices[i - 1] > max) {
        		min = prices[i - 1];
        		max = prices[i - 1];
        		
    		}  else if (prices[i -1] < min) {
    			min = prices[i - 1];
        		int tempMaxPro = max - min;
        		if (tempMaxPro > maxPro) {
        			maxPro = tempMaxPro;
        		}
        	}
    		maxPost[i - 1] = maxPro;
    	}
    	
    	maxPro = 0;
    	for (int i = 0; i < len; i++) {
    		int tempMaxPro = maxPre[i] + maxPost[i];
    		if (maxPro < tempMaxPro ) {
    			maxPro = tempMaxPro;
    		}
    	}
    	return maxPro;
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值