算法分析與設計課程作業第十九周#1

算法分析與設計課程作業第十九周#1

不知道要寫多少篇,就提前寫埋下週的。

123. Best Time to Buy and Sell Stock III

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

思路

考慮用兩個數組,
sell[i]表示在這天之前賣,最多能賺多少;
buy[i]表示這天之後買,最多能賺多少。
所求即是sell[i]+buy[i+1]的最大值。
具體代碼見下。

代碼

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