`

Best Time to Buy and Sell Stock I II III(C++实现)

 
阅读更多
// Best Time to Buy and Sell Stock I
 
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() < 2) return 0;
        int mj = 0, mjIdx = 0;
        int ret = 0;
        for(int i = 1; i < prices.size(); ++i) {
            if(prices[i] >= prices[i-1]) {
                mj = prices[i] - prices[mjIdx];
            } else {
                if(prices[i] < prices[mjIdx]) {
                    mjIdx = i; 
                }
            }
            ret = max(ret, mj);
        }
        return ret;
    }
};
 
 
// Best Time to Buy and Sell Stock II
 
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() < 2) return 0;
        int ms = 0;
        int ret = 0;
        for(int i = 1; i < prices.size(); ++i) {
            if(prices[i] >= prices[i-1]) {
                 ms += prices[i] - prices[i-1];
            } else {
                ret += ms;
                ms = 0;
            }
        }
        ret += ms;
        return ret;
    }
};
 
// Best Time to Buy and Sell Stock III
 
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() < 2) return 0;
        int n = prices.size();
        vector<int> l(n);
        vector<int> r(n);
        
        int minv = prices[0];
        l[0] = 0;
        for(int i = 1; i < n; ++i) {
            minv = min(minv, prices[i]);
            l[i] = max(l[i-1], prices[i] - minv);
        }
        
        int maxv = prices[n-1];
        r[n-1] = 0;
        for(int i = n-2; i >= 0; --i) {
            maxv = max(maxv, prices[i]);
            r[i] = max(r[i+1], maxv - prices[i]);
        }
        
        int ret = 0;
        for(int i = 0; i < n; ++i) {
            ret = max(ret, l[i] + r[i]);
        }
        
        return ret;
    }
};

 

 

 欢迎关注微信公众号——计算机视觉 

 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics