Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Created April 11, 2020 11:36
Show Gist options
  • Save manojnaidu619/36395436e26503d3bebcdbc4a7214ce2 to your computer and use it in GitHub Desktop.
Save manojnaidu619/36395436e26503d3bebcdbc4a7214ce2 to your computer and use it in GitHub Desktop.
Maximum subarray (Kadane's Algorithm) in python
# Done using Kadane's Algorithm
nums = [-2, -3, 4, -1, -2, 1, 5, -3] # Change array here
max_so_far,max_ending_here = 0,0
beg,end=0,0
for x in range(0,len(nums)):
max_ending_here += nums[x]
if max_ending_here > max_so_far:
max_so_far = max_ending_here
end=x+1
if max_ending_here < 0:
max_ending_here = 0
beg=x+1
print("Length of max subarray : ", max_so_far)
print("Max subarray", nums[beg:end])
# Time complexity, Space complexity = O(n), O(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment