feat: leetcode 刷题买卖股票最佳时机
This commit is contained in:
parent
eea70ac117
commit
32033709dc
37
leetcode/简单/买卖股票最佳时机(121).js
Normal file
37
leetcode/简单/买卖股票最佳时机(121).js
Normal 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]));
|
Loading…
x
Reference in New Issue
Block a user