Skip to content

Instantly share code, notes, and snippets.

@HauptJ
Created March 14, 2020 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HauptJ/8a2c57da079ff32cb38baf01c6c805d5 to your computer and use it in GitHub Desktop.
Save HauptJ/8a2c57da079ff32cb38baf01c6c805d5 to your computer and use it in GitHub Desktop.
Maximum Subarray Sum
class Solution:
# Dynamic Programming: Time: O(n) Space O(n)
def maxSubArrayDP(self, nums: List[int]) -> int:
if not nums:
return 0
maxSum = nums[0]
DP = [0]*len(nums) # DP will hold the max sum so far
DP[0] = maxSum
for i in range(1, len(nums), 1):
DP[i] = max(nums[i], DP[i-1]+nums[i])
maxSum = max(DP[i], maxSum)
return maxSum
# Optimized: Time: O(n) Space: O(1)
def maxSubArray(self, nums: List[int]) -> int:
if not nums:
return 0
maxSum = nums[0]
currSum = maxSum
for i in range(1, len(nums), 1):
currSum = max(nums[i], currSum + nums[i])
maxSum = max(currSum, maxSum)
return maxSum
@HauptJ
Copy link
Author

HauptJ commented Mar 14, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment