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
  • 相关阅读:
    闭包总结
    执行上下文总结
    下拉列表
    练习 九九乘法表
    JavaScript中break和continue的区别
    JaveScript遍历数组的方法
    将一个块级元素水平和垂直居中的方法
    ECMAScript 中最常见的一个问题是字符串连接的性能
    JS 一些题目 难点
    JS闭包
  • 原文地址:https://www.cnblogs.com/helloWaston/p/4494797.html
Copyright © 2011-2022 走看看