LearnFrenzy
Sign in Take a free test

Python Coding Interview Questions · Coding Problems – Arrays and Strings · Question 3

Maximum subarray sum with indices (Kadane) in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Find the contiguous subarray with the largest sum and return the sum and the subarray, handling all-negative input.

Solution
main.py Run
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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links