`

Best Time to Buy and Sell Stock I

 
阅读更多

question:

 

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.

 

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int n = prices.size();
        if(n <= 1) return 0;
        
        int maxAll = 0;
        int maxLast = 0;
        
        int maxJump = 0;
        int mjb = prices[0]; // max jump begin element
        
        vector<int>::iterator it = prices.begin();
        vector<int>::iterator li = it;
        it++;
        for(;it != prices.end(); it++, li++) {
            if(*it >= *li) {
                maxLast += *it - *li;
                maxJump += *it - *li;
            } else {
                maxLast = 0; 
                if(*it < mjb) {
                    mjb = *it;
                    maxJump = 0;
                } else {
                    maxJump += *it - *li;
                }
            }
            maxAll = max(maxAll, maxLast);
            maxAll = max(maxAll, maxJump);
        }
        return maxAll;
    }
    
};

 

0
4
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics