zoukankan      html  css  js  c++  java
  • [LeetCode 121]

    问题

    假设你有一个数组,其中的第i个元素表示一只股票在第i天的价格。

    如果只允许你完成一次交易(即买入并卖出股票一次),设计一个找出最大利润的算法。

    初始思路

    和122一样,基于买入与卖出股票的最佳时机III中的分析很容易得出答案。由于只允许进行一次交易,本题更加简单,我们只需按III中的方法不断更新最大利润即可。

     1 class Solution {
     2     public:
     3         int maxProfit(std::vector<int> &prices)
     4         {
     5             return CaculateProfit(prices).profit;
     6         }
     7         
     8     private:
     9         struct Profit
    10         {
    11             Profit() : profit(0), buyPrice(-1), buyDay(0), sellDay(0)
    12             {
    13             }
    14             
    15             int profit;
    16             int buyPrice;
    17             int buyDay;
    18             int sellDay;
    19         };
    20         
    21         Profit CaculateProfit(std::vector<int> &prices)
    22         {
    23             Profit currentProfit;
    24             Profit maxProfit;
    25             
    26             for(int day = 0; day < prices.size(); ++day)
    27             {
    28                 if(currentProfit.buyPrice == -1)
    29                 {
    30                     currentProfit.buyPrice = prices[day];
    31                     currentProfit.buyDay = day;
    32                     continue;
    33                 }
    34                 
    35                 currentProfit.profit = prices[day] - currentProfit.buyPrice;
    36                 currentProfit.sellDay = day;
    37                 
    38                 if(currentProfit.profit < 0)
    39                 {
    40                     currentProfit.buyPrice = prices[day];
    41                     currentProfit.buyDay = day;
    42                     currentProfit.profit = 0;
    43                 }
    44                 
    45                 if(currentProfit.profit > maxProfit.profit)
    46                 {
    47                     maxProfit = currentProfit;
    48                 }
    49             }
    50 
    51             return maxProfit;
    52         }
    53     };
    maxProfit
  • 相关阅读:
    transform:translate -50%解释
    无缝滚动条
    css二维画面练习-扑克牌
    css二维动画
    ORM了解
    socket总结
    2016/9/23总结电脑内容
    winform控件跨线程委托
    HttpRequestMessage
    vue设置每个页面的头部title
  • 原文地址:https://www.cnblogs.com/shawnhue/p/leetcode_121.html
Copyright © 2011-2022 走看看