# 买卖股票的最佳时机

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0

链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock

# 思路

解题连接

var maxProfit = function(prices) {
   // 数组长度
   let n = prices.length;
   // 卖出时的最大利润
   prices_out = 0;
   // 买入时的价格,prices[0]前面加个-负号
   prices_in = -prices[0]
   for(let i = 1; i < n; i++){
    	// 卖出时最大利润 = 买入价+当前价
       prices_out = Math.max(prices_out, prices_in + prices[i]);
       // 买入时价格,Math.max最终返回最大值-1,也就找到了买入的最低点
       prices_in = Math.max(prices_in, -prices[i]);
   }
   return prices_out
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

image-20210907134611441

最后更新时间: 6/20/2022, 10:48:50 PM