• 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     }
  • 相关阅读:
    小清新数论题泛做
    近日模考理数压轴题简记
    带边数的无向连通图计数
    ZJOI2019 简记
    SDOI2019 R2D2 题解
    [补档题解]后缀树节点数
    [BJ United Round 3] 押韵
    高维 DFT 算法(FWT 快速沃尔什变换)
    SDOI2019 R2D1 题解
    LOJ#6713. 「EC Final 2019」狄利克雷 k 次根 加强版
  • 原文地址:https://www.cnblogs.com/rogarlee/p/3420550.html
Copyright © 2020-2023  润新知