zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock @leetcode

    Plan A:

     1 int maxProfit(vector<int> &prices) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         int i;
     5         int res=0;
     6         if(prices.size() == 0 || prices.size()==1)
     7         {
     8             return 0;
     9         }
    10         vector<int> highestAfterThis;
    11         highestAfterThis.resize(prices.size()-1);
    12         for(i=highestAfterThis.size()-1;i>=0;--i)
    13         {
    14             if(i == highestAfterThis.size() -1)
    15                 highestAfterThis[i] = prices[prices.size()-1];
    16             else
    17             {
    18                 highestAfterThis[i] = prices[i+1]>highestAfterThis[i+1]?prices[i+1]:highestAfterThis[i+1];
    19             }
    20         }
    21         for(i=0;i<prices.size()-1;++i)
    22         {
    23             int tmp = highestAfterThis[i] - prices[i];
    24             if(tmp > res )res = tmp;
    25         }
    26         return res;
    27     }

    Plan B:

     1 int maxProfit(vector<int> &prices) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         int i;
     5         int res=0;
     6         if(prices.size() == 0 || prices.size()==1)
     7         {
     8             return 0;
     9         }
    10         int min=prices[0];
    11         for(i=0;i<prices.size();++i)
    12         {
    13             if(prices[i] < min) min = prices[i];
    14             if(prices[i] - min > res) res = prices[i] - min;
    15         }
    16         return res;
    17     }
  • 相关阅读:
    防御式编程
    Linux磁盘与文件系统管理
    更加抽象
    高质量的子程序
    Linux文件与目录管理
    抽象
    可以工作的类
    Linux的文件权限与目录配置
    条件、循环和其他语句
    软件构建中的设计
  • 原文地址:https://www.cnblogs.com/rogarlee/p/3420550.html
Copyright © 2011-2022 走看看