Python...two same concept but why is one slower?


  • 1
    I
    def maxSubArray(self, nums): 
          dp = [nums[0]]+[0]*(len(nums)-1)
          for i in range(1,len(nums)):
              dp[i] = nums[i] + dp[i-1] if dp[i-1] > 0 else nums[i]
          return max(dp)
    
    def maxSubArray(self, nums):
        dp = [nums[0]]+[0]*(len(nums)-1)
        max_sum = dp[0]
        for i in range(1,len(nums)):
            dp[i] = nums[i] + dp[i-1] if dp[i-1] > 0 else nums[i]
            max_sum = max(dp[i], max_sum)
        return max_sum
    

    Why is the first one faster than the second one?


  • 0
    S

    you calculate the max_sum in the loop


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.