37 lines
1.3 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.

/**
* https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/description/?envType=study-plan-v2&envId=top-interview-150
* @param {number[]} prices
* @return {number}
* 暴力解法:遍历整个数组,找到买入点和所有卖出点的利润,如果利润大于当前利润就更新最大利润,最后返回最大利润,会超时
*/
function f1(prices) {
let maxProfit = 0;
const size = prices.length;
for (let i = 0; i < size; i++) {
for (let j = i + 1; j < size; j++) {
if (prices[j] - prices[i] > maxProfit) maxProfit = prices[j] - prices[i];
}
}
return maxProfit;
}
/**
* @param {number[]} prices
* @return {number}
*单次遍历法定义两个变量一个maxProfit = 0一个minPrice=InfinitymaxProfit和上面的暴力法是一样的保存最大利润maxProfit
*表示的是买入的最小价格买入的越小后面如果遇到大于它的价格利润就越大如果利润比maxProfit还大就可以更新maxProfit了最后
*返回即可
*/
function f2(prices) {
let maxProfit = 0;
let minPrice = Infinity;
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;
}