algorighm/leetcode/简单/买卖股票最佳时机(121).js

38 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
示例 1
输入:[7,1,5,3,6,4]
输出5
解释:在第 2 天(股票价格 = 1的时候买入在第 5 天(股票价格 = 6的时候卖出最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
*/
/**
* @param {number[]} prices
* @return {number}
* 思路先设置一个变量minPrice 用于保存数组中最小的价格,初始值为无穷大,依次遍历数组,如果有元素比他小那么就
* 替换为当前元素,如果遍历的元素比他还大那就说明在“这一天”是可以卖掉的,但是利润不一定是最大的,多以我们还需要
* 一个全局变量 maxProfit来表示例如初始值为0如果这一天卖掉的利润比之前的最大利润大就可以替换为当前利润
* 最后返回当前利润
*/
function calculateProfit(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (const price of prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
return maxProfit;
}
console.log(calculateProfit([5, 2, 1, 34, 55]));