def max_subarray(nums):
best = current = nums[0]
start = best_start = best_end = 0
for i in range(1, len(nums)):
if nums[i] > current + nums[i]:
current, start = nums[i], i # start a new subarray here
else:
current += nums[i]
if current > best:
best, best_start, best_end = current, start, i
return best, nums[best_start:best_end + 1]
print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
print(max_subarray([-8, -3, -6]))
Output Verified by running it on Python 3
(6, [4, -1, 2, 1])
(-3, [-3])
Either extend the current subarray or start fresh, whichever is larger. Starting from nums[0] makes all-negative input work. O(n) time, O(1) space.
More Python Coding Interview Questions practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!