Finding the sub array that has maximum sum JavaScript

We are required to write a JavaScript function that takes in an array of Numbers. The array of numbers can contain both positive as well as negative numbers.

The purpose of our function is to find the sub array from the array (of any length), whose elements when summed gives the maximum sum. Then the function should return the sum of the elements of that subarray.

For example −

If the input array is −

const arr = [-2,1,-3,4,-1,2,1,-5,4];

Then the output should be −

const output = 6

because, [4,-1,2,1] has the largest sum of 6.


const arr = [-2,1,-3,4,-1,2,1,-5,4];
const maxSubArray = (arr = []) => {
   let sum = arr[0], max = arr[0];
   for (let i = 1; i < arr.length; ++i){
      sum = Math.max(sum + arr[i], arr[i]), max = Math.max(max, sum);
   return max;


And the output in the console will be −