[leetcode] Best Time to Buy and Sell Stock

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.

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

Idea:  find i,j, let price[j]-price[i] is maximized. 用一個min_value值存儲當前price最小值,max_value存儲當前profit最大值,用price[i]-min_value來不斷update max_value. (總是想當然用min和max……,如果這時候還需要調用min和max函數,就出問題了

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

Idea:  find all of the ascending substring

3. Design an algorithm to find the maximum profit. You may complete at most two transactions.

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        int len = prices.size();
        if (len <= 1)
            return 0;
        vector<int> prices_1;
        vector<int> prices_2;
        prices_1.resize(len);
        prices_2.resize(len);
        
        int min_value = prices[0];
        prices_1[0]=0;
        for(int i = 1; i < len; i++){
            prices_1[i] = max(prices_1[i-1],prices[i]-min_value);
            if (prices[i]<min_value)
                min_value = prices[i];
        }
        
        int max_value = prices[len-1];
        prices_2[len-1]=0;
        for(int i = len-2; i>=0; i--){
            prices_2[i] = max(prices_2[i+1],max_value-prices[i]);
            if (prices[i]> max_value)
                max_value = prices[i];
        }
        
        int sum = 0;
        for (int i = 0; i< len; i++){
            sum = max(sum, prices_1[i]+prices_2[i]);
        }
        return sum;
    }
};




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