
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Contiguous Sum of Subarray in JavaScript
We are required to write a JavaScript function that takes in an array of array of positive and negative integers. Since the array also contains negative elements, the sum of contiguous elements can possibly be negative or positive.
Our function should pick an array of contiguous elements from the array that sums the greatest. Finally, the function should return that array.
For example −
If the input array is −
const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
Then the maximum possible sum is 7 and the output subarray should be −
const output = [4, -1, -2, 1, 5];
Example
Following is the code -
const arr = [-2, -3, 4, -1, -2, 1, 5, -3]; const maximumSubarray = (arr = []) => { let max = -Infinity; let currentSum = 0; let maxStartIndex = 0; let maxEndIndex = arr.length - 1; let currentStartIndex = 0; arr.forEach((currentNumber, currentIndex) => { currentSum += currentNumber; if (max < currentSum) { max = currentSum; maxStartIndex = currentStartIndex; maxEndIndex = currentIndex; } if (currentSum < 0) { currentSum = 0; currentStartIndex = currentIndex + 1; } }); return arr.slice(maxStartIndex, maxEndIndex + 1); }; console.log(maximumSubarray(arr));
Output
Following is the output on console −
[ 4, -1, -2, 1, 5 ]
Advertisements