zoukankan      html  css  js  c++  java
  • 【LeetCode】121.Best Time to Buy and Sell Stock

    Say you have an array for which the ith element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    题目分析:

    做的时候,想用动态规划做,当时写不出比较好表达地递推式。因为最大值和最小值有一个前后关系:某一时刻最大值定下来后,想再移动最小值,则此时最大值也要改变,若只要改变最大值,最小值不受影响。这样子比较会比较混乱。

    改变思路:从后往前遍历,到下标i时,则表示第i天买入,这样赚到的最大利润是i+1天~n-1填最大股价减去第i天的。

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         //if (0 == prices.size())     return 0;
     5         int length = prices.size();
     6         int result = 0;
     7         int maxPrice = result;
     8         for (int i = length - 1; i >= 0; --i)
     9         {
    10             maxPrice = max(maxPrice, prices[i]);
    11             result = max(result, maxPrice - prices[i]);
    12         }
    13         return result;
    14     }
    15 };
    198 / 198 test cases passed.
    Status: 

    Accepted

    Runtime: 11 ms
    Submitted: 0 minutes ago
  • 相关阅读:
    流程控制语句
    第一周考点
    8.6
    8.5
    自用论文排版组合 = LyX2.2.2 + TeXLive2016
    解析几何图解
    概率论与数理统计图解.tex
    硕士研究生入学考试复试试卷答案.tex
    概率论与数理统计图解
    一月7日
  • 原文地址:https://www.cnblogs.com/helloWaston/p/4494797.html
Copyright © 2011-2022 走看看