Created
March 14, 2020 21:04
-
-
Save HauptJ/8a2c57da079ff32cb38baf01c6c805d5 to your computer and use it in GitHub Desktop.
Maximum Subarray Sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
53. Maximum Subarray
Walk Through - YouTube
Walk Through - Vimeo