Maximize sum of consecutive differences in a circular array

Pattern: Candy and assign cookies

medium

This is the same task as Maximum Sum of Absolute Difference: alternate small and large values around the circle, so the answer is 2 × (sum of the larger half - sum of the smaller half).

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Arrange the values in a circle to maximise the sum of |a[i] - a[i + 1]|, with the last value next to the first, and return that sum. [4, 2, 1, 8] gives 18. The catalogue has no practice link for this one.

Think first

  • In a circle, how many differences touch each value?
  • What would make a value count with a plus sign twice?
  • Which values should be the neighbours of the largest?

Hints

    Brute force, and why it fails

    Try every arrangement: O(n! × n).

    The key insight

    Each value sits in two differences; alternating puts the large half on the plus side of both and the small half on the minus side.

    Dry run

    10 
    21 
    42 
    83 

    arr = [4, 2, 1, 8]. Sorted: 1, 2, 4, 8.

    Step 1 of 3

    The plan

    sort a
    return sum over i < n / 2 of 2 × (a[n - 1 - i] - a[i])
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    Sorting dominates.

    Edge cases

    • One value: 0.
    • Two values: twice their difference.
    • An odd count: the middle value cancels out.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public long maxCircularSum(int[] arr) {
            int[] a = arr.clone();
            Arrays.sort(a);
            int n = a.length;
            long sum = 0;
            for (int i = 0; i < n / 2; i++) sum += 2L * (a[n - 1 - i] - a[i]);   // each big value sits between two small ones
            return sum;
        }
    }

    C++

    class Solution {
    public:
        long long maxCircularSum(vector<int>& arr) {
            vector<int> a(arr);
            sort(a.begin(), a.end());
            int n = static_cast<int>(a.size());
            long long sum = 0;
            for (int i = 0; i < n / 2; i++) sum += 2LL * (a[n - 1 - i] - a[i]);   // each big value sits between two small ones
            return sum;
        }
    };

    Python

    class Solution:
        def maxCircularSum(self, arr: list[int]) -> int:
            a, n = sorted(arr), len(arr)
            return sum(2 * (a[n - 1 - i] - a[i]) for i in range(n // 2))   # each big value sits between two small ones

    Common mistakes

    • Forgetting the wrap-around term from the last value back to the first.
    • Interleaving without sorting first.

    Similar problems