LeetCode 「中等」122.买卖股票的最佳时机 II

sankigan2025-2-19算法LeetCode

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

题目描述

给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

返回你能获得的 最大 利润 。

示例

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

输入:prices = [1,2,3,4,5]
输出:4

解答

遍历输入的股价,若第 i 天的价格比第 i - 1 天的价格高,那么我们就将第 i 天与第 i - 1 的价格差计入总利润中,直到遍历结束

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