121.122.123.188. Best Time to Buy and Sell Stock I II III IV

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

題目:最多一次買賣

思路:動規迭代,每天比較‘歷史最大收益’和(當前價-歷史最小价),然後比較‘歷史最小价’和‘當前價’來更新‘歷史最小价’

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

題目:無限多次買賣

思路:貪心,凡是有收益就賣了,再從新找‘最小价’;如果當前沒收益,則更新‘最小价’。

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null || prices.length<2) return 0;
        int sumPro=0, minPri=prices[0];
        for(int i=1; i<prices.length; i++){
            if(prices[i]>minPri) {
                sumPro+=prices[i]-minPri;
                minPri=prices[i];
            }else{
                minPri=prices[i];
            }
        }
        return sumPro;
    }
}

題目:最多賣2次

思路:正反兩次掃描,分別找到每天前後的最大利潤,疊加

public int maxProfit(int[] prices) {
        if(prices==null || prices.length<2) return 0; 
        int[] proFor = new int[prices.length]; 
        int[] proBack = new int[prices.length]; 
        int result = 0; 
        //forward
        int curMin=prices[0], maxBen=0; proFor[0] = 0;  
        for(int i = 1; i< prices.length; i++){  
            maxBen = Math.max(maxBen, prices[i]-curMin);  
            proFor[i] = maxBen;
            curMin = Math.min(curMin, prices[i]);  
        }  
        //backword
        int curMax=prices[prices.length-1]; maxBen=0; proBack[prices.length-1] = 0;
        for(int i = prices.length-2; i>=0 ; i--){  
            maxBen = Math.max(maxBen, curMax - prices[i]);
            proBack[i] = maxBen;
            curMax = Math.max(curMax, prices[i]);  
        }
        for(int i=0; i<prices.length; i++){
            result = Math.max(result,proFor[i]+proBack[i]);
        }
        return result;
    }


題目:k次買賣

難題,沒搞懂, 參考:
http://liangjiabin.com/blog/2015/04/leetcode-best-time-to-buy-and-sell-stock.html
http://blog.csdn.net/linhuanmars/article/details/23236995

思路:第i天最多交易j次的最大利潤dp[i][j]有三種情況:1.i天交易賠錢,所以不交易,則等於i-1天最多交易j次的最大利潤dp[i-1][j],2.i天交易掙錢,a)連續掙dp[i-1][j]+diff,b) 間隔掙錢 dp[i-1][j-1]+diff


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章