LeetCode 「简单」121.买卖股票的最佳时机

sankigan2025-2-19算法LeetCode

买卖股票的最佳时机open in new window

题目描述

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0

示例

输入:[7,1,5,3,6,4]
输出:5

输入:[7,6,4,3,1]
输出:0

解答

暴力法(超时)

Code
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
  let lk = 0;
  let maxIncome = 0;

  while (lk < prices.length) {
    maxIncome = Math.max(maxIncome, Math.max(...prices.slice(lk + 1)) - prices[lk]);
    lk++;
  }

  return maxIncome;
};

一次遍历

如果我们真的在买卖股票,我们肯定会想:如果我是在历史最低点买的股票就好了!在题目中,我们只要用一个变量记录一个历史最低价格 minprice,我们就可以假设自己的股票是在那天买的,那么我们在第 i 天卖出股票能得到的利润就是 prices[i] - minprice

Code
var maxProfit = function(prices) {
  let minprice = prices[0];
  let maxprofit = 0;
  for (let i = 1; i < prices.length; ++i) {
    minprice = Math.min(minprice, prices[i]);
    maxprofit = Math.max(maxprofit, prices[i] - minprice);
  }
  return maxprofit;
}
更新于 2025/3/20 23:23:29