算法分析與設計課程作業第七週#1#2

算法分析與設計課程作業第七週#1#2

這周選了以動態規劃爲標籤的股票買賣問題系列的前兩題來做,以下爲題目:

121. Best Time to Buy and Sell Stock

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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

思路

只能買賣一次,所以問題就是要求後面值減前面值的最大的最大差值。因爲比較簡單,就直接給出遞歸求解公式如下(由到前i-1次價格買賣的最大利潤求出到第i次價格買賣的最大利潤):
profit[i] = max(prices[i]-min{prices[j]|j=1,...,i-1}, profit[i-1])
事實上profit不需用一個數組存儲,只用一個變量也行,每次都更新profit即可。

代碼

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

122. Best Time to Buy and Sell Stock 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 (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).

思路

對比前一題,這一題可以買賣股票任意多次,所以遍歷數組,每次將遍歷到的極大值減去其之前的極小值即可。此爲第一個版本代碼。
而其實,遍歷數組,如果遍歷到的值比起前一個值大,就考慮之前以前一個值價格買入,該值價格賣出,也能得到同樣的結果。

122第一個版本代碼

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

122第二個版本代碼

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty() || prices.size() == 1){
            return 0;
        }
        int profit = 0;
        for(int i = 1; i < prices.size(); i++){
            if(prices[i] > prices[i-1]){
                profit += prices[i] - prices[i-1];
            }
        }
        return profit;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章