- Related Questions & Answers
- Finding the maximum in a nested array - JavaScript
- Finding the sum of unique array values - JavaScript
- Maximum size of sub-array that satisfies the given condition in C++
- JavaScript Finding the third maximum number in an array
- Maximum size of sub-array that satisfies the given condition in C++ program
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST in C++
- Finding the third maximum number within an array in JavaScript
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST in C++ program
- Finding sum of alternative elements of the array in JavaScript
- Maximum sum Bi-tonic Sub-sequence in C++
- Finding two numbers that produce equal to the sum of rest in JavaScript
- Finding sum of a range in an array JavaScript
- Maximum subarray sum in circular array using JavaScript
- How to find the column that has the largest sum in R?
- Maximum value K such that array has at-least K elements that are >= K in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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; }; console.log(maxSubArray(arr));

And the output in the console will be −

6

Advertisements