Maximize the sum of arr*i

Pattern: Candy and assign cookies

medium

Rearrange the array to maximise the sum of arr[i] × i. Larger values should get larger indexes, so sort ascending; any crossed pair could be swapped to increase the sum.

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

The problem

Rearrange the array to make the sum of arr[i] × i (0-based i) as large as possible and return that sum. [5, 3, 2, 4, 1] gives 40. The GFG version takes the answer modulo 10⁹ + 7; this guide's values are small, so it returns the sum itself. The catalogue has no practice link for this one.

Think first

  • Which value should get the largest index?
  • What happens if a bigger value sits at a smaller index than a smaller value?
  • So what order is best?

Hints

    Brute force, and why it fails

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

    The key insight

    Pairing large with large maximises a sum of products (the rearrangement inequality), so sorted order is best.

    Dry run

    10 
    21 
    32 
    43 
    54 

    arr = [5, 3, 2, 4, 1]. Sorted: 1, 2, 3, 4, 5.

    Step 1 of 3

    The plan

    sort ascending
    return sum of a[i] × i
    

    Complexity

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

    Sorting dominates.

    Edge cases

    • Negative values: they go to the small indexes.
    • One value: 0.
    • Equal values.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public long maxSum(int[] arr) {
            int[] a = arr.clone();
            Arrays.sort(a);                         // the biggest value gets the biggest index
            long sum = 0;
            for (int i = 0; i < a.length; i++) sum += (long) a[i] * i;
            return sum;
        }
    }

    C++

    class Solution {
    public:
        long long maxSum(vector<int>& arr) {
            vector<int> a(arr);
            sort(a.begin(), a.end());               // the biggest value gets the biggest index
            long long sum = 0;
            for (size_t i = 0; i < a.size(); i++) sum += static_cast<long long>(a[i]) * static_cast<long long>(i);
            return sum;
        }
    };

    Python

    class Solution:
        def maxSum(self, arr: list[int]) -> int:
            return sum(x * i for i, x in enumerate(sorted(arr)))   # the biggest value gets the biggest index

    Common mistakes

    • Sorting descending.
    • Overflow in 32 bits for large inputs.

    Similar problems