Maximum subarray sum in circular array using JavaScript

We need to write a JavaScript function that finds the maximum possible sum of a subarray in a circular array. In a circular array, the last element connects to the first element, creating additional subarray possibilities.

Problem Statement

Given an array of integers, find the maximum sum of any non-empty subarray. The array is considered circular, meaning we can wrap around from the end to the beginning.

Example:

Input: [2, -2, 3, -1]
Output: 4
Explanation: Maximum subarray is [3, -1, 2] (wrapping around)

Algorithm Approach

The solution uses two key insights:

  • Case 1: Maximum subarray doesn't wrap around - use standard Kadane's algorithm
  • Case 2: Maximum subarray wraps around - find minimum subarray and subtract from total sum
Circular Array Maximum Subarray 2 -2 3 -1 circular Case 1: No wrap [3] = 3 Case 2: Wrap [3, -1, 2] = 4 1. Find max subarray (Kadane's) 2. Find min subarray, subtract from total 3. Return maximum of both cases

Implementation

const arr = [2, -2, 3, -1];

const maxSubarraySumCircular = (arr = []) => {
    let max = arr[0];
    let min = arr[0];
    let currentMax = max;
    let currentMin = min;
    let sum = arr[0];
    
    for (let i = 1; i < arr.length; i++) {
        currentMax = arr[i] + Math.max(currentMax, 0);
        max = Math.max(max, currentMax);
        
        currentMin = arr[i] + Math.min(currentMin, 0);
        min = Math.min(min, currentMin);
        
        sum += arr[i];
    }
    
    // If all elements are negative, return max element
    return max < 0 ? max : Math.max(max, sum - min);
};

console.log(maxSubarraySumCircular(arr));
4

How It Works

The algorithm simultaneously tracks:

  • currentMax/max: Standard Kadane's algorithm for maximum subarray
  • currentMin/min: Modified Kadane's for minimum subarray
  • sum: Total array sum

The final result is either the maximum subarray (no wrap) or total sum minus minimum subarray (wrap case).

Additional Examples

// Example 1: All negative numbers
console.log(maxSubarraySumCircular([-3, -2, -5, -1])); // -1

// Example 2: Mixed positive/negative
console.log(maxSubarraySumCircular([5, -3, 5])); // 10

// Example 3: Single element
console.log(maxSubarraySumCircular([3])); // 3
-1
10
3

Time and Space Complexity

Metric Complexity Explanation
Time O(n) Single pass through array
Space O(1) Only uses constant extra variables

Conclusion

The circular maximum subarray problem extends Kadane's algorithm by considering wrap-around cases. This solution efficiently handles both scenarios in a single pass with optimal time and space complexity.

Updated on: 2026-03-15T23:19:00+05:30

261 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements