首页  >  文章  >  后端开发  >  破解 LeetCode 。买卖股票的最佳时机 II

破解 LeetCode 。买卖股票的最佳时机 II

WBOY
WBOY原创
2024-08-05 21:42:12301浏览

在我不断提高 LeetCode 技能的过程中,我解决了“买卖股票的最佳时机 II”问题。此挑战是经典“买入和卖出股票 II 的最佳时机”问题(LeetCode 121)的后续挑战,但有一个关键的区别:*您可以执行多个交易以最大化利润。
*

视觉方法

在深入研究代码之前,我发现在白板上可视化问题非常有帮助。这使我能够将问题分解为更小、更易于管理的步骤。

Cracking the LeetCode . Best Time to Buy and Sell Stock II

贪婪方法

考虑到进行无限交易的灵活性,贪婪的方法似乎很有前途。核心思想很简单:每当股票价格比前一天上涨时,我们就认为这是一个潜在的获利机会。通过将所有这些价格差异相加,我们可以有效地计算出最大利润。

Python实现

这是实现这种贪婪策略的Python代码:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0

        for i in range(1, len(prices)):
            if prices[i] > prices[i-1]:
                profit+=prices[i] - prices[i-1]

        return profit

JavaScript 实现

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    var profit = 0;
    for (var i = 1; i < prices.length; i++)
    {
    if(prices[i] > prices[i-1])
    {
        profit += Number(prices[i] - prices[i-1])
    }
    }

    return profit
};

时间和空间复杂度

  • 这种方法的时间复杂度为 O(N),其中 N = 数组长度。
  • 当我们就地比较时,空间复杂度是 N(1)。

以上是破解 LeetCode 。买卖股票的最佳时机 II的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn