Advertisement
smj007

Untitled

Feb 13th, 2024
1,196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. class Solution:
  2.     def maxSubArray(self, nums: List[int]) -> int:
  3.  
  4.         n = len(nums)
  5.         dp = [0]*(n+1)
  6.         max_so_far = -math.inf
  7.  
  8.         for i in range(1, n+1):
  9.             dp[i] = max(dp[i-1] + nums[i-1], nums[i-1])
  10.             max_so_far = max(dp[i], max_so_far)
  11.  
  12.         return max_so_far
  13.  
  14.  
  15. class Solution:
  16.     def maxSubArray(self, nums: List[int]) -> int:
  17.        
  18.         prev1 = 0
  19.         max_so_far = -math.inf
  20.        
  21.         for n in nums:
  22.  
  23.             max_ending_here = max(prev1 + n, n)
  24.             # made the mistake here of including prev1: max_ending_here = max(prev1 + n, n, prev1)
  25.             # if prev1 is included above, it defeates the entire purpose of a continguous array
  26.             max_so_far = max(max_ending_here, max_so_far)
  27.             prev1 = max_ending_here
  28.  
  29.         return max_so_far
  30.  
  31. class Solution:
  32.     def maxSubArray(self, nums: List[int]) -> int:
  33.        
  34.         current_sum = 0
  35.         max_so_far = -math.inf
  36.        
  37.         for n in nums:
  38.  
  39.             max_ending_here = max(current_sum + n, n)
  40.             # made the mistake here of including prev1: max_ending_here = max(prev1 + n, n, prev1)
  41.             # if prev1 is included above, it defeates the entire purpose of a continguous array
  42.             max_so_far = max(max_ending_here, max_so_far)
  43.             current_sum = max_ending_here
  44.  
  45.         return max_so_far
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement