1. 程式人生 > >LeetCode.Best Time to Buy and Sell Stock II 買賣股票的最佳時機 II

LeetCode.Best Time to Buy and Sell Stock II 買賣股票的最佳時機 II

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 (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation:
Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation:
Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation:
In this case, no transaction is done, i.e. max profit = 0.

股票就是一個大坑,讓我去買股票,我是不會去的,這輩子都不可能買股票。如果上帝能像本題這樣把所有的價格走勢都告訴我了,那肯定要試一試。要想股票收益最大低買高賣就行,所以我們只要遍歷陣列找到漲價的點就是購買的時機。
低買高賣有兩種情況,一種是漲了就賣,一種是一直漲到最高再賣。
第一種情況,找出所有當前比前一天高的價格,然後計算差值和,就是最大收益。

C++程式碼解法1:

class Solution { 
public: 
    int maxProfit(vector<int>& prices) { 
    	if(prices.empty()  ||  prices.size()  ==  1) 
    		return 0;
    	int maxprofit = 0;
    	for(int i = 1;  i  <  prices.size();  i++){
    		if(prices[i-1] < prices[i]){
    			maxprofit += prices[i] - prices[i-1];
    		}
    	}
    	return maxprofit;
    };  

Python程式碼解法1:

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) == 0 or len(prices) == 1:
            return 0
      	maxprofit = 0 # 總收益
        for i in range(1, len(prices)):
            if prices[i-1] < prices[i]:
                maxprofit += prices[i] - prices[i-1]
        return maxprofit

第二種情況,要麻煩一點,首先要找到買入時機,然後再找到賣出時機。買入時機其實就是當前的價格比第二天低,賣出時機那就是當前價格比第二天高。

C++程式碼解法2:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty() || prices.size() == 1) 
            return 0;
        int maxprofit = 0;
        int flag = -1;
        for(int i = 0; i < prices.size() - 1; i++){
            if(prices[i] <= prices[i+1]){ // 明天價格要漲或橫盤
                if(flag == -1){ // 未持有
                    // 買進
                    flag = prices[i];
                }
                // 如果明天已是最後一天
                if(i == prices.size() - 2){
                    if(flag != -1){ // 已持有
                        // 賣出
                        maxprofit += prices[i+1] - flag;
                        flag = -1;
                    }
                }  
            }else{ // 明天價格要跌
                if(flag != -1){ // 手裡持有股票
                    // 趕緊拋
                    maxprofit += prices[i] - flag;
                    flag = -1;
                }
            }
        }
        return maxprofit;
    }
};

Python程式碼解法2:

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) == 0 or len(prices) == 1:
            return 0
        maxprofit = 0 # 總收益
        buyprice = -1 # 持有股票價格
        for i in range(0, len(prices)-1):
            # 先判斷是否持有
            if buyprice == -1: # 未持有
                # 判斷明天是否漲價,漲價則買入,跌價則繼續空賬號
                if prices[i] < prices[i+1]:
                    buyprice = prices[i]
            else: # 已持有
                # 判斷明天是否跌價,是則丟擲
                if prices[i] > prices[i+1]:
                    maxprofit += prices[i] - buyprice
                    buyprice = -1
        
        # 最後還要判斷一下最後一天的情況
        if buyprice != -1:
            maxprofit += prices[len(prices)-1] - buyprice
            buyprice = -1
        return maxprofit