Home > Back-end >  Python Solution to Leet Code Problem is Failing when Submitted but works on custom input?
Python Solution to Leet Code Problem is Failing when Submitted but works on custom input?

Time:09-24

My Solution is failing at one test case each time I'm trying to submit, but when I'm giving the same input for which it is failing as custom input it is working as expected.

Can someone help me with this?

Please check this screenshot. Screenshot This is Question Number 121 from LeetCode.

Code:

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]

CodePudding user response:

You are using static attributes, which you should make sure to reset on every run of maxProfit.

Things go wrong because you don't reset Solution.maxSP to zero, and so max(Solution.maxSP, prices[i 1]) is using a value that was the result of a previous run of maxProfit

So make sure to reset Solution.maxSP to zero.

  • Related