Javascript Program for Largest Sum Contiguous Subarray
Last Updated :
30 Aug, 2024
Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum.

Kadane's Algorithm:
Initialize:
max_so_far = INT_MIN
max_ending_here = 0
Loop for each element of the array
(a) max_ending_here = max_ending_here + a[i]
(b) if(max_so_far < max_ending_here)
max_so_far = max_ending_here
(c) if(max_ending_here < 0)
max_ending_here = 0
return max_so_far
Explanation:
The simple idea of Kadane's algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive-sum compare it with max_so_far and update max_so_far if it is greater than max_so_far
Lets take the example:
{-2, -3, 4, -1, -2, 1, 5, -3}
max_so_far = max_ending_here = 0
for i=0, a[0] = -2
max_ending_here = max_ending_here + (-2)
Set max_ending_here = 0 because max_ending_here < 0
for i=1, a[1] = -3
max_ending_here = max_ending_here + (-3)
Set max_ending_here = 0 because max_ending_here < 0
for i=2, a[2] = 4
max_ending_here = max_ending_here + (4)
max_ending_here = 4
max_so_far is updated to 4 because max_ending_here greater
than max_so_far which was 0 till now
for i=3, a[3] = -1
max_ending_here = max_ending_here + (-1)
max_ending_here = 3
for i=4, a[4] = -2
max_ending_here = max_ending_here + (-2)
max_ending_here = 1
for i=5, a[5] = 1
max_ending_here = max_ending_here + (1)
max_ending_here = 2
for i=6, a[6] = 5
max_ending_here = max_ending_here + (5)
max_ending_here = 7
max_so_far is updated to 7 because max_ending_here is
greater than max_so_far
for i=7, a[7] = -3
max_ending_here = max_ending_here + (-3)
max_ending_here = 4
Program:
JavaScript
// JavaScript program to find maximum
// contiguous subarray
// Function to find the maximum
// contiguous subarray
function maxSubArraySum(a, size) {
let maxint = Math.pow(2, 53)
let max_so_far = -maxint - 1
let max_ending_here = 0
for (let i = 0; i < size; i++) {
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here)
max_so_far = max_ending_here
if (max_ending_here < 0)
max_ending_here = 0
}
return max_so_far
}
// Driver code
let a = [-2, -3, 4, -1, -2, 1, 5, -3]
console.log("Maximum contiguous sum is",
maxSubArraySum(a, a.length))
// This code is contributed by AnkThon
OutputMaximum contiguous sum is 7
Another approach:
JavaScript
function maxSubarraySum(arr, size) {
let max_ending_here = 0, max_so_far = Number.MIN_VALUE;
for (let i = 0; i < size; i++) {
// Include current element to previous subarray only
// when it can add to a bigger number than itself.
if (arr[i] <= max_ending_here + arr[i]) {
max_ending_here += arr[i];
}
// Else start the max subarray from current element
else {
max_ending_here = arr[i];
}
if (max_ending_here > max_so_far) {
max_so_far = max_ending_here;
}
}
return max_so_far;
}
// Example usage:
const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
const size = arr.length;
const result = maxSubarraySum(arr, size);
console.log("Maximum subarray sum is:", result);
OutputMaximum subarray sum is: 7
Complexity Analysis:
Time Complexity: O(n)
Algorithmic Paradigm: Dynamic Programming
Following is another simple implementation suggested by Mohit Kumar. The implementation handles the case when all numbers in the array are negative.
JavaScript
// print largest
// contiguous array sum
function maxSubArraySum(a, size) {
let max_so_far = a[0];
let curr_max = a[0];
for (let i = 1; i < size; i++) {
curr_max = Math.max(a[i], curr_max + a[i]);
max_so_far = Math.max(max_so_far, curr_max);
}
return max_so_far;
}
// Driver code
let a = [-2, -3, 4, -1, -2, 1, 5, -3];
let n = a.length;
console.log("Maximum contiguous sum is ", maxSubArraySum(a, n));
OutputMaximum contiguous sum is 7
To print the subarray with the maximum sum, we maintain indices whenever we get the maximum sum.
JavaScript
// javascript program to print largest
// contiguous array sum
function maxSubArraySum(a, size) {
let max_so_far = Number.MIN_VALUE;
let max_ending_here = 0, start = 0, end = 0, s = 0;
for (i = 0; i < size; i++) {
max_ending_here += a[i];
if (max_so_far < max_ending_here) {
max_so_far = max_ending_here;
start = s;
end = i;
}
if (max_ending_here < 0) {
max_ending_here = 0;
s = i + 1;
}
}
console.log("Maximum contiguous sum is " + max_so_far);
console.log("Starting index " + start);
console.log("Ending index " + end);
}
// Driver code
let a = [-2, -3, 4, -1, -2, 1, 5, -3];
let n = a.length;
maxSubArraySum(a, n);
// This code is contributed by Rajput-Ji
OutputMaximum contiguous sum is 7
Starting index 2
Ending index 6
Kadane's Algorithm can be viewed both as a greedy and DP. As we can see that we are keeping a running sum of integers and when it becomes less than 0, we reset it to 0 (Greedy Part). This is because continuing with a negative sum is way more worse than restarting with a new range. Now it can also be viewed as a DP, at each stage we have 2 choices: Either take the current element and continue with previous sum OR restart a new range. These both choices are being taken care of in the implementation.
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(1)
Now try the below question:
Given an array of integers (possibly some elements negative), write a C program to find out the *maximum product* possible by multiplying 'n' consecutive integers in the array where n ≤ ARRAY_SIZE. Also, print the starting point of the maximum product subarray.
Please refer complete article on Largest Sum Contiguous Subarray for more details!
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read