思路
- 1.先定义两个变量记录最小价格和最大利润,初始化为数组第一个和0
- 2.for循环判断是不是小于最小价格以及利润是不是大于最大利润,是就替换
/*
* @lc app=leetcode.cn id=121 lang=javascript
*
* [121] 买卖股票的最佳时机
*/
// @lc code=start
/**
* @param {number[]} prices
* @return {number}
* 1.先定义两个变量记录最小价格和最大利润,初始化为数组第一个和0
* 2.for循环判断是不是小于最小价格以及利润是不是大于最大利润,是就替换
*/
var maxProfit = function (prices) {
if (prices.length === 0) return 0
let minPrice = prices[0],
maxProfit = 0
for (let i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i]
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice
}
}
return maxProfit
}
// @lc code=end
// @after-stub-for-debug-begin
module.exports = maxProfit;
// @after-stub-for-debug-end