feat: leetcode 刷题买卖股票最佳时机

This commit is contained in:
LouisFonda 2025-03-04 00:36:33 +08:00
parent eea70ac117
commit 32033709dc
Signed by: yigencong
GPG Key ID: 29CE877CED00E966

View File

@ -0,0 +1,37 @@
/*
给定一个数组 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]));