Javascript Program for Maximum circular subarray sum
Last Updated :
18 Sep, 2024
Given n numbers (both +ve and -ve), arranged in a circle, find the maximum sum of consecutive numbers.
Examples:
Input: a[] = {8, -8, 9, -9, 10, -11, 12}
Output: 22 (12 + 8 - 8 + 9 - 9 + 10)
Input: a[] = {10, -3, -4, 7, 6, 5, -4, -1}
Output: 23 (7 + 6 + 5 - 4 -1 + 10)
Input: a[] = {-1, 40, -14, 7, 6, 5, -4, -1}
Output: 52 (7 + 6 + 5 - 4 - 1 - 1 + 40)
Method 1
There can be two cases for the maximum sum:
- Case 1: The elements that contribute to the maximum sum are arranged such that no wrapping is there. Examples: {-10, 2, -1, 5}, {-2, 4, -1, 4, -1}. In this case, Kadane's algorithm will produce the result.
- Case 2: The elements which contribute to the maximum sum are arranged such that wrapping is there. Examples: {10, -12, 11}, {12, -5, 4, -8, 11}. In this case, we change wrapping to non-wrapping. Let us see how. Wrapping of contributing elements implies non-wrapping of non-contributing elements, so find out the sum of non-contributing elements and subtract this sum from the total sum. To find out the sum of non-contributions, invert the sign of each element and then run Kadane's algorithm.
Our array is like a ring and we have to eliminate the maximum continuous negative that implies maximum continuous positive in the inverted arrays. Finally, we compare the sum obtained in both cases and return the maximum of the two sums.
The following are implementations of the above method.
JavaScript
// javascript program for maximum contiguous circular sum problem
function kadane(a, n) {
let res = 0;
let x = a[0];
for (i = 0; i < n; i++) {
res = Math.max(a[i], res + a[i]);
x = Math.max(x, res);
}
return x;
}
// lets write a function for calculating max sum in circular manner as discuss
// above
function reverseKadane(a, n) {
let total = 0;
// taking the total sum of the array elements
for (i = 0; i < n; i++) {
total += a[i];
}
// inverting the array
for (i = 0; i < n; i++) {
a[i] = -a[i];
}
// finding min sum subarray
let k = kadane(a, n);
// max circular sum
let ress = total + k;
// to handle the case in which all elements are negative
if (total == -k) {
return total;
}
else {
return ress;
}
}
let a = [11, 10, -20, 5, -3, -5, 8, -13, 10];
let n = 9;
if (n == 1) {
console.log("Maximum circular sum is " + a[0]);
}
else {
console.log("Maximum circular sum is "
+ Math.max(kadane(a, n), reverseKadane(a, n)));
}
OutputMaximum circular sum is 31
Complexity Analysis:
- Time Complexity: O(n), where n is the number of elements in the input array.
As only linear traversal of the array is needed. - Auxiliary Space: O(1).
As no extra space is required.
Note that the above algorithm doesn't work if all numbers are negative, e.g., {-1, -2, -3}. It returns 0 in this case. This case can be handled by adding a pre-check to see if all the numbers are negative before running the above algorithm.
Method 2
Approach:
In this method, modify Kadane's algorithm to find a minimum contiguous subarray sum and the maximum contiguous subarray sum, then check for the maximum value between the max_value and the value left after subtracting min_value from the total sum.
Algorithm:
- We will calculate the total sum of the given array.
- We will declare the variable curr_max, max_so_far, curr_min, min_so_far as the first value of the array.
- Now we will use Kadane's Algorithm to find the maximum subarray sum and minimum subarray sum.
- Check for all the values in the array:-
- If min_so_far is equaled to sum, i.e. all values are negative, then we return max_so_far.
- Else, we will calculate the maximum value of max_so_far and (sum - min_so_far) and return it.
The implementation of the above method is given below.
JavaScript
// JavaScript program for the above approach
// The function returns maximum
// circular contiguous sum in a[]
function maxCircularSum(a, n) {
// Corner Case
if (n == 1)
return a[0];
// Initialize sum variable which store total sum of the array.
let sum = 0;
for (let i = 0; i < n; i++) {
sum += a[i];
}
// Initialize every variable with first value of array.
let curr_max = a[0], max_so_far = a[0], curr_min = a[0], min_so_far = a[0];
// Concept of Kadane's Algorithm
for (let i = 1; i < n; i++) {
// Kadane's Algorithm to find Maximum subarray sum.
curr_max = Math.max(curr_max + a[i], a[i]);
max_so_far = Math.max(max_so_far, curr_max);
// Kadane's Algorithm to find Minimum subarray sum.
curr_min = Math.min(curr_min + a[i], a[i]);
min_so_far = Math.min(min_so_far, curr_min);
}
if (min_so_far == sum)
return max_so_far;
// returning the maximum value
return Math.max(max_so_far, sum - min_so_far);
}
// Driver program to test maxCircularSum()
let a = [11, 10, -20, 5, -3, -5, 8, -13, 10];
let n = a.length;
console.log("Maximum circular sum is " + maxCircularSum(a, n));
OutputMaximum circular sum is 31
Complexity Analysis:
- Time Complexity: O(n), where n is the number of elements in the input array.
As only linear traversal of the array is needed. - Auxiliary Space: O(1).
As no extra space is required.
Please refer complete article on Maximum circular subarray sum for more details!
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Maximum Subarray Sum - Kadane's Algorithm Given an integer array arr[], find the subarray (containing at least one element) which has the maximum possible sum, and return that sum.Note: A subarray is a continuous part of an array.Examples:Input: arr[] = [2, 3, -8, 7, -1, 2, 3]Output: 11Explanation: The subarray [7, -1, 2, 3] has the largest
8 min read
Introduction to JavaScript JavaScript is a versatile, dynamically typed programming language used for interactive web applications, supporting both client-side and server-side development, and integrating seamlessly with HTML, CSS, and a rich standard library.JavaScript is a single-threaded language that executes one task at
7 min read
JSON Web Token (JWT) A JSON Web Token (JWT) is a standard used to securely transmit information between a client (like a frontend application) and a server (the backend). It is commonly used to verify users' identities, authenticate them, and ensure safe communication between the two. JWTs are mainly used in web apps an
7 min read
Frontend Developer Interview Questions and Answers Frontend development is an important part of web applications, and it is used to build dynamic and user-friendly web applications with an interactive user interface (UI). Many companies are hiring skilled Frontend developers with expertise in HTML, CSS, JavaScript, and modern frameworks and librarie
15+ min read
JavaScript Coding Questions and Answers JavaScript is the most commonly used interpreted, and scripted Programming language. It is used to make web pages, mobile applications, web servers, and other platforms. Developed in 1995 by Brendan Eich. Developers should have a solid command over this because many job roles need proficiency in Jav
15+ min read
Top 95+ Javascript Projects For 2025 JavaScript is a lightweight, cross-platform programming language that powers dynamic and interactive web content. From real-time updates to interactive maps and animations, JavaScript brings web pages to life.Here, we provided 95+ JavaScript projects with source code and ideas to provide hands-on ex
4 min read
Functions in JavaScript Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9)); // output: 15Function Syntax
5 min read
JavaScript Exercises, Practice Questions and Solutions JavaScript Exercise covers interactive quizzes, tracks progress, and enhances coding skills with our engaging portal. Ideal for beginners and experienced developers, Level up your JavaScript proficiency at your own pace. Start coding now! A step-by-step JavaScript practice guide for beginner to adva
3 min read