[leetcode]Best Time to Buy and Sell Stock II

#include <iostream>
#include <vector>
using namespace std;

//总体思路,每当有一个上升趋势,就要抓住它
//那么维护2个迭代器,left和right,left指向阶段性最低(靠左),right指向阶段性最高(靠右)
//需要注意的是迭代器在使用的过程中不要超出了范围,例如下面注释部分特别需要注意
class Solution {
public:
    int maxProfit(vector<int> &prices) {  
        vector<int>::const_iterator left = prices.begin();
        vector<int>::const_iterator right;
        int max = 0;

        while(left != prices.end()){
            while(left < prices.end()-1 && *left > *(left+1))//这里保证每次left和left+1比较都不会发生下标异常
                left++;

            right = left + 1;
            while((right < prices.end()-1 && *right < *(right+1))){//这里保证每次right和right+1比较都不会发生下标异常
                right++;
            }
            if ((right == prices.end()-1 && *right < *left) || right == prices.end())//到这里,right可能是end()-1,也可能是end()(这种情况发生在:left本来就是end()-1了,然后right = left+1;)
                break;

            max += *right - *left;
            left = right+1;
        }

        return max;
    }
};


int main()
{
    vector<int> prices;
    prices.push_back(2);
    prices.push_back(1);
    Solution s;
    s.maxProfit(prices);
    return 0;
}

 

 

 

 

 

 

EOF

posted on 2012-12-19 21:11  kkmm  阅读(263)  评论(0编辑  收藏  举报