Maximize sum of consecutive differences in a circular array

Last Updated : 17 Aug, 2026

Given an array arr[ ] of positive elements. Consider the array as a circular array, meaning the element after the last element is the first element of the array. The task is to find the maximum sum of the absolute differences between consecutive elements with shuffling of array elements allowed i.e. shuffle the array elements and make [a1..an] such order that  |a1 – a2| + |a2 – a3| + …… + |an-1 – an| + |an – a1is maximized.

Examples: 

Input: arr[] = [4, 2, 1, 8]
Output: 18
Explanation: After Shuffling, we get [1, 8, 2, 4]. Sum of absolute difference between consecutive elements after rearrangement = |1 - 8| + |8 - 2| + |2 - 4| + |4 - 1| = 7 + 6 + 2 + 3 = 18.

Input: arr[] = [10, 12]
Output: 4
Explanation: No need of rearrangement. Sum of absolute difference between consecutive elements = |10 - 12| + |12 - 10| = 2 + 2 = 4.

Try It Yourself
redirect icon

[Naive Approach] Generate All Permutations - O(n! * n) Time and O(n) Space

The idea is to generate all possible arrangements of the array and calculate the circular sum of absolute differences for each arrangement. We keep track of the maximum sum obtained among all permutations.

Working of Approach:

  • Generate every possible permutation of the given array.
  • For each permutation, calculate differences between consecutive elements.
  • Also calculate the difference between the last and first elements.
  • Keep the maximum sum among all permutations.
C++
#include <iostream>
#include <vector>
using namespace std;

long long res = 0;

// Calculate the circular sum for the current permutation
long long calculate(vector<int> &arr)
{
    int n = arr.size();
    long long sum = 0;

    for (int i = 0; i < n; i++)
    {
        // Add absolute difference with the next element
        sum += abs(arr[i] - arr[(i + 1) % n]);
    }

    return sum;
}

// Generate all possible permutations
void generate(vector<int> &arr, int idx)
{
    int n = arr.size();

    // If a complete permutation is formed
    if (idx == n)
    {
        res = max(res, calculate(arr));
        return;
    }

    for (int i = idx; i < n; i++)
    {
        // Place arr[i] at the current position
        swap(arr[idx], arr[i]);

        // Generate remaining permutations
        generate(arr, idx + 1);

        // Backtrack
        swap(arr[idx], arr[i]);
    }
}

// Function to find the maximum sum
long long maxSum(vector<int> &arr)
{
    generate(arr, 0);

    return res;
}

int main()
{

    vector<int> arr = {4, 2, 1, 8};

    cout << maxSum(arr) << endl;

    return 0;
}
Java
import java.util.Arrays;

public class GFG {
    static long res = 0;

    // Calculate the circular sum for the current
    // permutation
    static long calculate(int[] arr)
    {
        int n = arr.length;
        long sum = 0;

        for (int i = 0; i < n; i++) {
            // Add absolute difference with the next element
            sum += Math.abs(arr[i] - arr[(i + 1) % n]);
        }

        return sum;
    }

    // Generate all possible permutations
    static void generate(int[] arr, int idx)
    {
        int n = arr.length;

        // If a complete permutation is formed
        if (idx == n) {
            res = Math.max(res, calculate(arr));
            return;
        }

        for (int i = idx; i < n; i++) {
            // Place arr[i] at the current position
            swap(arr, idx, i);

            // Generate remaining permutations
            generate(arr, idx + 1);

            // Backtrack
            swap(arr, idx, i);
        }
    }

    static void swap(int[] arr, int i, int j)
    {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // Function to find the maximum sum
    static long maxSum(int[] arr)
    {
        generate(arr, 0);

        return res;
    }

    public static void main(String[] args)
    {
        int[] arr = { 4, 2, 1, 8 };

        System.out.println(maxSum(arr));
    }
}
Python
import itertools

res = 0

# Calculate the circular sum for the current permutation
def calculate(arr):
    n = len(arr)
    sum = 0

    for i in range(n):
        # Add absolute difference with the next element
        sum += abs(arr[i] - arr[(i + 1) % n])

    return sum

# Generate all possible permutations
def generate(arr, idx):
    n = len(arr)

    # If a complete permutation is formed
    if idx == n:
        global res
        res = max(res, calculate(arr))
        return

    for i in range(idx, n):
        # Place arr[i] at the current position
        arr[idx], arr[i] = arr[i], arr[idx]

        # Generate remaining permutations
        generate(arr, idx + 1)

        # Backtrack
        arr[idx], arr[i] = arr[i], arr[idx]

# Function to find the maximum sum
def maxSum(arr):
    generate(arr, 0)

    return res

if __name__ == "__main__":
    arr = [4, 2, 1, 8]

    print(maxSum(arr))
C#
using System;

public class GFG {
    static long res = 0;

    // Calculate the circular sum for the current
    // permutation
    static long calculate(int[] arr)
    {
        int n = arr.Length;
        long sum = 0;

        for (int i = 0; i < n; i++) {
            // Add absolute difference with the next element
            sum += Math.Abs(arr[i] - arr[(i + 1) % n]);
        }

        return sum;
    }

    // Generate all possible permutations
    static void generate(int[] arr, int idx)
    {
        int n = arr.Length;

        // If a complete permutation is formed
        if (idx == n) {
            res = Math.Max(res, calculate(arr));
            return;
        }

        for (int i = idx; i < n; i++) {
            // Place arr[i] at the current position
            swap(arr, idx, i);

            // Generate remaining permutations
            generate(arr, idx + 1);

            // Backtrack
            swap(arr, idx, i);
        }
    }

    static void swap(int[] arr, int i, int j)
    {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // Function to find the maximum sum
    static long maxSum(int[] arr)
    {
        generate(arr, 0);

        return res;
    }

    public static void Main()
    {
        int[] arr = { 4, 2, 1, 8 };

        Console.WriteLine(maxSum(arr));
    }
}
JavaScript
let res = 0;

// Calculate the circular sum for the current permutation
function calculate(arr)
{
    let n = arr.length;
    let sum = 0;

    for (let i = 0; i < n; i++) {
        // Add absolute difference with the next element
        sum += Math.abs(arr[i] - arr[(i + 1) % n]);
    }

    return sum;
}

// Generate all possible permutations
function generate(arr, idx)
{
    let n = arr.length;

    // If a complete permutation is formed
    if (idx == n) {
        res = Math.max(res, calculate(arr));
        return;
    }

    for (let i = idx; i < n; i++) {
        // Place arr[i] at the current position
        [arr[idx], arr[i]] = [ arr[i], arr[idx] ];

        // Generate remaining permutations
        generate(arr, idx + 1);

        // Backtrack
        [arr[idx], arr[i]] = [ arr[i], arr[idx] ];
    }
}

// Function to find the maximum sum
function maxSum(arr)
{
    generate(arr, 0);

    return res;
}

// Driver Code
let arr = [ 4, 2, 1, 8 ];

console.log(maxSum(arr));

Output
18

[Expected Approach] Using Sorting and Greedy Pairing - O(n log n) Time and O(1) Space

The idea is to sort the array and pair the smallest elements with the largest elements. This maximizes the absolute differences. Since the array is circular, every selected difference contributes twice to the answer.

Consider the sorted permutation of the given array a1, a1, a2,...., an - 1, an such that a1 < a2 < a3.... < an - 1 < an. Now to obtain the answer having maximum sum of difference between consecutive element, arrange element in following manner: 
a1, an, a2, an-1,...., an/2, a(n/2) + 1 

We can observe that the above arrangement produces the optimal answer, as all a1, a2, a3,....., a(n/2)-1, an/2 are subtracted twice while a(n/2)+1 , a(n/2)+2, a(n/2)+3,....., an - 1, an are added twice. 

Note:  a(n/2)+1 This term is considered only for even n because for odd n, it is added once and subtracted once and hence cancels out. 

Working of Approach:

  • Sort the array in ascending order.
  • Pair the smallest element with the largest element.
  • Pair the second smallest with the second largest, and so on.
  • Each pair contributes twice because of the circular arrangement.
  • Add these contributions to get the maximum sum.

Let us understand with an example:
Input: arr[] = [4, 2, 1, 8]

  • After sorting, the array becomes [1, 2, 4, 8].
  • For i = 0, sum = 0 - 2(1) + 2(8) = 14.
  • For i = 1, sum = 14 - 2(2) + 2(4) = 18.
  • The loop runs for the first half of the array, so the final sum is 18.
  • Hence, the maximum sum of absolute differences is 18.
C++
#include <iostream>
#include <vector>
using namespace std;

long long maxSum(vector<int> &arr)
{
    long long sum = 0;
    int n = arr.size(); // Size of the array

    // Sorting the array in ascending order
    sort(arr.begin(), arr.end());

    // Looping over the first half of the array
    for (int i = 0; i < n / 2; i++)
    {
        // Subtracting twice the current element and adding twice
        // the element at the opposite end of the array to the sum
        sum -= (2 * arr[i]);
        sum += (2 * arr[n - i - 1]);
    }

    // Returning the maximum sum
    return sum;
}

int main()
{

    vector<int> arr = {4, 2, 1, 8};

    cout << maxSum(arr) << endl;

    return 0;
}
Java
import java.util.Arrays;

class GFG {

    // Function to find the maximum sum of the array
    // elements
    public long maxSum(Long[] arr)
    {
        long sum = 0;
        int n = arr.length;

        // Sorting the array in ascending order
        Arrays.sort(arr);

        // Looping over the first half of the array
        for (int i = 0; i < n / 2; i++) {
            
            // Subtract twice the smaller element
            // and add twice the larger element
            sum -= 2 * arr[i];
            sum += 2 * arr[n - i - 1];
        }

        return sum;
    }

    public static void main(String[] args)
    {
        GFG obj = new GFG();

        Long[] arr = { 4L, 2L, 1L, 8L };

        long ans = obj.maxSum(arr);

        System.out.println(ans);
    }
}
Python
def maxSum(arr):
    sum = 0
    n = len(arr) # Size of the array

    # Sorting the array in ascending order
    arr.sort()

    # Looping over the first half of the array
    for i in range(n // 2):
        
        # Subtracting twice the current element and adding twice
        # the element at the opposite end of the array to the sum
        sum -= (2 * arr[i])
        sum += (2 * arr[n - i - 1])

    # Returning the maximum sum
    return sum

if __name__ == '__main__':
    arr = [4, 2, 1, 8]

    print(maxSum(arr))
C#
using System;
using System.Linq;

public class GFG {
    public static long maxSum(int[] arr)
    {
        long sum = 0;
        int n = arr.Length; // Size of the array

        // Sorting the array in ascending order
        Array.Sort(arr);

        // Looping over the first half of the array
        for (int i = 0; i < n / 2; i++) {
            
            // Subtracting twice the current element and
            // adding twice the element at the opposite end
            // of the array to the sum
            sum -= (2 * arr[i]);
            sum += (2 * arr[n - i - 1]);
        }

        // Returning the maximum sum
        return sum;
    }

    public static void Main()
    {
        int[] arr = { 4, 2, 1, 8 };

        Console.WriteLine(maxSum(arr));
    }
}
JavaScript
function maxSum(arr)
{
    let sum = 0;
    let n = arr.length; // Size of the array

    // Sorting the array in ascending order
    arr.sort((a, b) => a - b);

    // Looping over the first half of the array
    for (let i = 0; i < Math.floor(n / 2); i++) {
        
        // Subtracting twice the current element and adding
        // twice the element at the opposite end of the
        // array to the sum
        sum -= (2 * arr[i]);
        sum += (2 * arr[n - i - 1]);
    }

    // Returning the maximum sum
    return sum;
}

// Driver Code
let arr = [ 4, 2, 1, 8 ];
console.log(maxSum(arr));

Output
18
Comment