1. 程式人生 > >[LeetCode] 22. Best Time to Buy and Sell Stock II Java

[LeetCode] 22. Best Time to Buy and Sell Stock II Java

股票 log ive highlight transacti ever 方法 size 可能

題目:

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

題意及分析:假設有一個數組,它的第i個元素是一個給定的股票在第i天的價格。設計一個算法來找到最大的利潤。你可以完成盡可能多的交易(多次買賣股票)。然而,你不能同時參與多個交易(你必須在再次購買前出售股票)。對於某天來說,如果第二天的價格高於當前價格那麽就可以買,然後第二天賣出,收益為價格差,依次類推,直到倒數第二天,可以證明這樣可以得到最大利潤。所以可以直接從頭到尾掃描prices,如果price[i] – price[i-1]大於零則計入最後的收益中,這就是貪心法。但是這個會違反“不能同一天買賣的規則”,例如3天的價格分別為1,2,3,那麽按上述算法就會在2那天同一天買賣了。但是 正確的做法應該是: 第1天買第3天賣。雖然兩種方法數字結果是對的,但是邏輯不一樣。。

代碼:

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length==0||prices.length==1) return 0;
        int res=0;		
        for(int i=0;i<prices.length-1;i++){
        	if(prices[i+1]>prices[i])
        		res+=prices[i+1]-prices[i];
        }
        // System.out.println(res);
        return res;
    }
}

但是這樣違反了題目說的不能在同一天包含買入和賣出,所以可以先找到遞減的局部最低點,再找到遞增的局部最高點,算一次加和,然後再這麽找。這樣就能保證買賣不會在同一天了。。

代碼:

public class Solution {
    public static int maxProfit(int[] prices) {
        int len = prices.length;
        if(len <= 1)
            return 0;
        int total=0;		//總收入
        int i=0;		//當前所在位置
        
        while(i<len-1){
        	int buy,sell;		//記錄買入賣出時間
        	while(i<len-1&&prices[i+1]<prices[i]){		//找到局部最小點
        		i++;
        	}
        	buy=i;		//買入點
        	i++;		//賣出點至少在買入點的下一個點
        	while(i<len&&prices[i]>=prices[i-1]){  //找到局部最大點
        		i++;
        	}
        	sell=--i;	//賣出點
        	total +=prices[sell]-prices[buy];
        }
        return total;
    }
}

  

  

  

  

[LeetCode] 22. Best Time to Buy and Sell Stock II Java