Maximum sum of absolute difference of an array

Pattern: Candy and assign cookies

medium

Arrange the values in a circle to maximise the sum of differences between neighbours, including last and first. Alternate small and large values: each large value then counts twice with a plus sign and each small one twice with a minus, giving 2 × (sum of the larger half - sum of the smaller half).

The problem

Rearrange the array to make |a[0] - a[1]| + |a[1] - a[2]| + … + |a[n - 1] - a[0]| as large as possible, and return it. The sum includes the wrap-around term from the last value to the first. [1, 2, 4, 8] gives 18.

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

    Every value appears in two differences. The best you can hope for is the larger half counted twice positive and the smaller half twice negative, and alternating reaches it.

    Dry run

    10 
    21 
    42 
    83 

    arr = [1, 2, 4, 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 maxSumDifference(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 maxSumDifference(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 maxSumDifference(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