- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 < arr.length; ++i){ sum = Math.max(sum + arr[i], arr[i]), max = Math.max(max, sum); }; return max; }; console.log(maxSubArray(arr));
Output
And the output in the console will be −
6
Advertisements