Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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.
Example
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 Output
And the output in the console will be −
6
Advertisements
