Maximum Subarray Sum

The "Maximum Subarray Sum" problem asks us to find the contiguous subarray within an array of numbers that has the largest sum. For example, given the array [-1, 3, -5, 4, 6], the largest sum would be 11, achieved by taking the subarray [3, -5, 4, 6].


Given an array of n elements, find the maximum sum of a contiguous subarray.
Example input: [1, -3, 2, 1, -1]
Example output: 3


This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
def max_subarray(arr):
    max_sum = 0
    current_sum = 0
    for i in range(len(arr)):
        current_sum += arr[i]
        if current_sum > max_sum:
            max_sum = current_sum
        if current_sum < 0:
            current_sum = 0
    return max_sum

print(max_subarray([1, -3, 2, 1, -1]))

A.I. Evaluation of the Solution

The candidate's solution correctly finds the maximum sum of a contiguous subarray. The approach is to keep track of the current sum and update the maximum sum if the current sum is greater than the maximum sum. If the current sum is negative, then the current sum is reset to 0.

Evaluated at: 2022-11-19 10:15:47