zoukankan      html  css  js  c++  java
  • [Leetcode] Best Time to Buy Stock

    考虑,股票的价格是不断变化的,卖出只能在买入后进行。而且只能买入卖出一次。

    开始的时候想扫一遍,求最大最小,但是肯定不会这么简单。你484傻

    因为只能卖出一次,若i天卖出,可能的盈利值是, prices[i] - min,就是今天的价格。

    再将这个值与之前可能的最大值比较,可以得到 第i天可能的最大值。

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if (prices.size() <= 1) return 0;
            int minPrice = prices[0];
            int n = prices.size();
            
            int maxProfit = 0;
            
            for (int i =0; i<n; ++i) {
                minPrice = min(minPrice, prices[i]);
                maxProfit = max(maxProfit,prices[i] - minPrice);
            }
            
            return maxProfit;
        }
    };
    

      

  • 相关阅读:
    平衡的括号(栈)
    二叉树遍历
    Ohana Cleans Up0101
    Missing number
    Django框架之模板层
    Django框架之路由层、视图层
    Django框架
    Django初识
    前端之bootstrap
    前端之BOM、DOM
  • 原文地址:https://www.cnblogs.com/shenbingyu/p/4912883.html
Copyright © 2011-2022 走看看