Created
April 11, 2020 11:36
-
-
Save manojnaidu619/36395436e26503d3bebcdbc4a7214ce2 to your computer and use it in GitHub Desktop.
Maximum subarray (Kadane's Algorithm) in python
This file contains hidden or 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
# 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