Find the Largest Sum of a Contiguous Subarray

This problem asks you to find the largest sum of a contiguous subarray within a given array of integers. For example, given the array [-2, 1, -3, 4, - 1, 2, 1, -5, 4], the largest sum of a contiguous subarray would be 6 (4 + -1 + 2 + 1 = 6).

Problem

Given an array of integers, find the largest sum of a contiguous subarray.
Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The solution is to iterate through the array and keep track of the current sum and the max sum.
// If the current sum is less than 0, then we reset the current sum to 0.
// If the current sum is greater than the max sum, then we update the max sum.
// This solution is optimal because we only iterate through the array once.

function maxSubArray(arr) {
  let currentSum = 0;
  let maxSum = 0;

  for (let i = 0; i < arr.length; i++) {
    currentSum += arr[i];
    if (currentSum < 0) {
      currentSum = 0;
    }
    if (currentSum > maxSum) {
      maxSum = currentSum;
    }
  }

  return maxSum;
}

console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]));

A.I. Evaluation of the Solution

The candidate's solution is correct and solves the problem. The candidate's approach is also optimal, as they only iterate through the array once.

Evaluated at: 2022-11-20 10:16:02