leetcode --- js版本IT@程序员猿媛程序员

leetcode-Easy-27-DP-Best Time to

2019-04-03  本文已影响2人  石头说钱

题目

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.

数组中,任意取一个数为买入价格,另外取一个数(这个数必须为前面所取数后面的数)为卖出价格,求能获得的最大利润

Input: [7,1,5,3,6,4]
Output: 5  // 6 - 1所得
// 为什么不能7 - 1
//因为必须先买才能卖,买入价格如果是7,卖出价格就必须是7后面的数,
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

var maxProfit = function(prices) {
    let max = 0
    let buy = prices[0]
    for(price of prices){
        // 保证买入的价格是最小的
        buy = Math.min(buy,price)
        // 没遇到一个新价格计算一次卖出的利润,然后对比前面卖出的利润,取最大的
        max = Math.max(max, price - buy)
    }
    return max
};
var res = maxProfit()
上一篇 下一篇

猜你喜欢

热点阅读