【问题标题】:Python Solution to Leet Code Problem is Failing when Submitted but works on custom input?Leet Code问题的Python解决方案在提交时失败但适用于自定义输入?
【发布时间】:2021-11-17 06:08:02
【问题描述】:

每次我尝试提交时,我的解决方案都会在一个测试用例中失败,但是当我提供与自定义输入相同的失败输入时,它会按预期工作。

有人可以帮我解决这个问题吗?

请查看此屏幕截图。 Screenshot 这是 LeetCode 的第 121 题。

代码:

class Solution:
    dp = []
    maxSP = 0
    def calcProf(self, prices, i, n):
        #dp[n-1] = 0 is the base case.
        if i < 0:
            return
        dp = Solution.dp
        
        Solution.maxSP = max(Solution.maxSP, prices[i+1])
        prof = Solution.maxSP - prices[i]
        dp[i] = max(prof, dp[i+1])
        
        self.calcProf(prices, i-1, n)

    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        if n == 1:
            return 0
        Solution.dp = [0] * (n)
        
        self.calcProf(prices, n-2, n)
        print("MaxSP: ", Solution.maxSP)
        print("dp: ", Solution.dp)
        return Solution.dp[0]

【问题讨论】:

  • 你需要解释它应该做什么。
  • calc_prof 代替 calcProf
  • 另外,用 max_sp 代替 maxSP
  • @rv.kvetch 这有什么改变?它适用于自定义输入相同的测试用例。
  • @rv.kvetch 没关系。请尝试将代码复制/粘贴到 Leet-Code 问题 121 并修改大小写,看看它是否适合您。

标签: python arrays recursion dynamic-programming


【解决方案1】:

您正在使用静态属性,您应该确保在每次运行 maxProfit 时重置它。

出现问题是因为您没有将 Solution.maxSP 重置为零,因此 max(Solution.maxSP, prices[i+1]) 使用的值是之前运行 maxProfit 的结果

所以请务必将Solution.maxSP 重置为零。

【讨论】:

  • 我尝试在设置 Solution.dp = [0] * n 的代码上方添加 Solution.dp = []。在maxProfit 函数中,但它没有解决问题。
  • 错过了,但maxSP没有重置。查看更新的答案。
  • 是的,非常感谢 trincot 和 @sahasra62 帮助我。
猜你喜欢
  • 2022-01-24
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多