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
  • 相关阅读:
    Catch That Cow POJ 3278(BFS)
    python的各种推导式(列表推导式、字典推导式、集合推导式)
    贝叶斯神经网络
    浅谈贝叶斯
    置换检验
    Python的基本用法
    字符串和编码
    开启新篇章
    无偏博弈类问题
    PAT1103
  • 原文地址:https://www.cnblogs.com/helloWaston/p/4494797.html
Copyright © 2011-2022 走看看