
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Using Kadane’s algorithm to find maximum sum of subarray in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers (both positive and negative), arr, as the first and the only argument.
Our function should return the maximum sum of any subarray in linear time
The local_maximum at any arbitrary index i is the maximum of arr[i] and the sum of arr[i] and local_maximum at index i - 1.
This is what we are going to apply to find the maximum subarray sum within an array in linear time.
For example, if the input to the function is −
Input
const arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
Output
const output = 6;
Output Explanation
Because the subarray with maximum sum is −
[4, -1, 2, 1]
Example
Following is the code −
const arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]; const maxSequence = (arr = []) => { let currentSum = 0 let maxSum = 0 for (let elem of arr) { const nextSum = currentSum + elem maxSum = Math.max(maxSum, nextSum) currentSum = Math.max(nextSum, 0) } return maxSum }; console.log(maxSequence(arr));
Output
6
- Related Questions & Answers
- Python Program to solve Maximum Subarray Problem using Kadane’s Algorithm
- C++ Program to Implement Kadane’s Algorithm
- Maximum Subarray Sum using Divide and Conquer algorithm in C++
- Maximum contiguous sum of subarray in JavaScript
- Maximum subarray sum in circular array using JavaScript
- Program to find maximum ascending subarray sum using Python
- Fleury’s Algorithm
- kasai’s Algorithm
- Manacher’s Algorithm
- Find Maximum Sum Strictly Increasing Subarray in C++
- Program to find maximum absolute sum of any subarray in Python
- C++ Program to Find the maximum subarray sum using Binary Search approach
- Repeated sum of Number’s digits in JavaScript
- Difference Between Prim’s and Kruskal’s Algorithm
- Maximum subarray sum in O(n) using prefix sum in C++
Advertisements