Maximum subarray sum in circular array using JavaScript


Problem

We are required to write a JavaScript function that takes in an array of integers, arr, as the first and the only argument.

We can consider this array arr to be a circular array, which means the last element of the array will be followed by the first. Our function should find and return the maximum possible sum of a non-empty subarray of arr.

For example, if the input to the function is

Input

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

Output

const output = 4;

Output Explanation

Because the desired subarray is [3, -1, 2]

Example

 Live Demo

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]
   }
   return max < 0 ? max : Math.max(max, sum - min)
}
console.log(maxSubarraySumCircular(arr));

Output

4

Updated on: 23-Apr-2021

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements