zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    Invariant 在于,如果第i 天和第j 天分别是最高收益的买入点和卖出点,那么prices[i] 必然是[0, j] 区间内价格的最低点。

    只用遍历一次,用当前找到的最低价格来计算收益,并更新收益最大值,同时更新价格最低点。遍历完成之后即得结果。

    /**
     * @param {number[]} prices
     * @return {number}
     */
    var maxProfit = function(prices) {
        var n = 0;
        var lowest = prices[0];
        prices.forEach(function(p) {
            n = Math.max(n, p - lowest);
            lowest = Math.min(lowest, p);
        });
        return n;
    };
  • 相关阅读:
    数组指针和指针数组的区别
    C++虚函数
    C++容器
    红黑树
    COM RTS/CTS, DTR/DSR
    linux和windows多线程的异同
    socket
    C++vector使用
    select函数详解
    linux下头文件
  • 原文地址:https://www.cnblogs.com/agentgamer/p/5407680.html
Copyright © 2011-2022 走看看