Skip to content

Instantly share code, notes, and snippets.

@iamprayush
Last active August 20, 2020 06:49
Show Gist options
  • Save iamprayush/5817e48dd6fd5a2a02a8603c98f1af8f to your computer and use it in GitHub Desktop.
Save iamprayush/5817e48dd6fd5a2a02a8603c98f1af8f to your computer and use it in GitHub Desktop.
Maximum subarray
class Solution:
def without_dp_array(self, arr: List[int]) -> int:
n = len(arr)
best = max(arr)
curr = 0
for ele in arr:
if ele > curr + ele:
curr = ele
else:
curr += ele
best = max(best, curr)
return best
def with_dp_array(self, arr: List[int]) -> int:
n = len(arr)
# dp[i] = max sum for arr[...i]
dp = [0] * n
dp[0] = arr[0]
for i in range(1, n):
dp[i] = max(dp[i - 1] + arr[i], arr[i])
return max(dp)
@iamprayush
Copy link
Author

Divide and conquer for this is also quite interesting: (https://www.youtube.com/watch?v=yBCzO0FpsVc)
maxSum(l, r) = max(maxSum(0, l), maxSum(r, n), maxSuff(0, l) + maxPref(r, n)
This would be nlogn

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