zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    python编程设计模式之接口类和抽象类
    python进阶之面向对象初识
    python进阶之异常处理
    python模块之包
    python模块之序列化模块
    python基础二 ---类型转换 ,字符串,列表,元祖,for,range,enumerate
    python基础一
    TCP协议的三次握手
    随机数Math.random()
    Vue.js内部响应式原理探究
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2825523.html
Copyright © 2011-2022 走看看