股票买卖问题,

Best Time to Buy and Sell Stock III

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

题意:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。最多交易两次,手上最多只能持有一支股票,求最大收益。

分析:动态规划法。以第i天为分界线,计算第i天之前进行一次交易的最大收益preProfit[i],和第i天之后进行一次交易的最大收益postProfit[i],最后遍历一遍,max{preProfit[i] + postProfit[i]} (0≤i≤n-1)就是最大收益。第i天之前和第i天之后进行一次的最大收益求法同Best Time to Buy and Sell Stock I。

代码:时间O(n),空间O(n)。

 

 

解决方案一:

比较巧妙的方案

class Solution {
    public int maxProfit(int[] prices) {
        
         int n=prices.length;
        
         if(prices.length<2)return 0;
        
     	//第i天之前的最大利益
    	int[] preProfit = new int[n];
    	//第i天之后的最大利益
    	int[] postProfit = new int[n];
    	//总的最大利润
    	int max = Integer.MIN_VALUE;
    	
    	//如果今天卖出之后,当前的最大利益小于之前的,则不卖出。否则今天卖出,最大利益得到更新
    	int minBuy = prices[0];
    	for(int i = 1;i=0;i--){
    		maxSell = Math.max(maxSell, prices[i]);
    		postProfit[i] = Math.max(postProfit[i+1], maxSell-prices[i]);
    	}
    	//求出两次交易的和,与总的最大利润进行比较
    	for(int i = 0;i

 下面参考了leetcode上的比较优秀的解答方案

解决方案二:

class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length < 2) {
            return 0;
        }
        
        int hold1 = 0 - prices[0];
        int notHold1 = 0;
        int hold2 = notHold1 - prices[0];
        int notHold2 = 0;
        
        for(int i = 1; i < prices.length; i++) {
            notHold2 = Math.max(notHold2, hold2 + prices[i]);
            hold2 = Math.max(hold2, notHold1 - prices[i]);
            notHold1 = Math.max(notHold1, hold1 + prices[i]);
            hold1 = Math.max(hold1, 0 - prices[i]);
        }
        
        return notHold2;
    }
}

解决方案三:

该方案在测试集里运行时间为2ms

class Solution {
    public int maxProfit(int[] prices) {
        
        int buy1 = Integer.MAX_VALUE;
        int sell1 = 0;
        int buy2 = Integer.MAX_VALUE;
        int sell2 = 0;
        
        for(int p : prices) {
            
            buy1 = Math.min(buy1, p);
            sell1 = Math.max(sell1, p - buy1);
            buy2 = Math.min(buy2, p - sell1);
            sell2 = Math.max(sell2, p-buy2);
        }
        
        return sell2;
    }
}

参考来源:

https://blog.csdn.net/u014609111/article/details/53508905

https://blog.csdn.net/ChenVast/article/details/78950392

https://blog.csdn.net/u012351768/article/details/51577272

https://leetcode.com/submissions/detail/173275367/

你可能感兴趣的:(数据结构算法)