Maximize Greatness of an Array

Medium Arrays & Hashing Greedy

Reported atNvidiaTwilioUKG

Maximize Greatness of an Array is a medium arrays & hashing problem solved with the greedy pattern. The best approach, optimal (n minus the highest frequency), runs in O(n) time and O(n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (greedy matching with a used array) up.

Problem

You are given an integer array nums (0-indexed). You may rearrange its values in any order you like, giving a new array perm that holds exactly the same numbers.

The greatness of perm is the number of indexes i where perm[i] > nums[i]: the positions where the rearranged array holds a strictly larger number than the original one did.

Return the largest greatness you can reach with a single rearrangement.

Examples

Example 1

Input
nums = [1,3,5,2,1,3,1]
Output
4
Why
One best arrangement is perm = [2,5,1,3,3,1,1]. It beats nums at indexes 0 (2 > 1), 1 (5 > 3), 3 (3 > 2) and 4 (3 > 1). The value 1 appears three times, and at most 7 - 3 = 4 positions can be won.

Example 2

Input
nums = [1,2,3,4]
Output
3
Why
perm = [2,3,4,1] wins at the first three positions. The 4 can never be beaten, because nothing in the array is larger.

Example 3

Input
nums = [5,5,5]
Output
0
Why
Every value is the same, so no rearrangement can put a strictly larger number anywhere.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^9

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (greedy matching with a used array)O(n^2)O(n)
Sort and two pointersO(n log n)O(1)
Optimal (n minus the highest frequency)O(n)O(n)

1Brute force (greedy matching with a used array)

TimeO(n^2)Sorting costs O(n log n), and then each of the n values may scan up to n numbers.
SpaceO(n)The sorted copy and the used array each hold n entries.

Sort a copy of the values. Go through them from smallest to largest, and beat each one with the smallest unused number that is strictly larger. Spending the smallest possible winner keeps the bigger numbers free for the bigger values still to come, so this greedy choice is never worse than any other. Searching for that number by scanning the whole array makes it slow.

  1. sorted is a sorted copy of nums, and used marks the numbers already placed as winners.
  2. For each i from left to right: scan j from i + 1 for the first unused sorted[j] with sorted[j] > sorted[i].
  3. If one is found, mark it used and add one to greatness.
  4. Return greatness.
class Solution {
    public int maximizeGreatness(int[] nums) {
        int n = nums.length;
        int[] sorted = nums.clone();
        Arrays.sort(sorted);
        boolean[] used = new boolean[n];
        int greatness = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (!used[j] && sorted[j] > sorted[i]) {
                    used[j] = true;
                    greatness++;
                    break;
                }
            }
        }
        return greatness;
    }
}

2Sort and two pointers

TimeO(n log n)Sorting dominates; the pass after it is linear.
SpaceO(1)Only a pointer, apart from the space the sort itself uses.

The same greedy without the search. In the sorted array, the values waiting to be beaten are taken from the left in order, and so are the winners. Walk through the sorted numbers as possible winners. A pointer matched marks the smallest value not yet beaten. If the current number is strictly larger than sorted[matched], it beats that value and matched moves on; otherwise it is too small to beat anything left and is simply skipped. The number of values beaten is the answer.

  1. Sort nums. matched = 0.
  2. For each x in the sorted array: if x > nums[matched], add one to matched.
  3. Return matched.
class Solution {
    public int maximizeGreatness(int[] nums) {
        Arrays.sort(nums);
        int matched = 0;
        for (int x : nums) {
            if (x > nums[matched]) matched++;
        }
        return matched;
    }
}

3Optimal (n minus the highest frequency)

TimeO(n)One pass, with constant expected work per number in the hash map.
SpaceO(n)The map can hold up to n different values.

Let v be the value that appears most often, m times. Every win puts a number on top of a strictly smaller one, so in each win either the winner is bigger than v or the loser is smaller than v (if neither, both would equal v, which is not a win). There are n - m numbers that are not v, and each takes part in at most one win on its side, so there are at most n - m wins. That many is always reachable: sort the values and shift them m places, so each number receives the one m positions further right; no value has more than m copies, so the receiver is always strictly larger. The answer is n - m, and counting needs no sort at all.

  1. Count how often each value appears with a hash map, tracking the largest count most.
  2. Return n - most.
class Solution {
    public int maximizeGreatness(int[] nums) {
        Map<Integer, Integer> freq = new HashMap<>();
        int most = 0;
        for (int x : nums) {
            int c = freq.getOrDefault(x, 0) + 1;
            freq.put(x, c);
            most = Math.max(most, c);
        }
        return nums.length - most;
    }
}

Edge cases to test

  • A single element: it can only sit on itself, so the answer is 0
  • All values equal: the answer is 0
  • All values distinct: everything except the largest can be beaten, so the answer is n - 1
  • Many copies of the smallest value, or of the largest value: the most frequent value decides the answer wherever it sits
  • Already sorted or reverse sorted input: the order of nums never matters, only the multiset of values
  • Zeros are allowed: 0 can beat nothing, but anything positive beats it

Hints

Hint 1

The order of nums does not matter for the answer: only which values appear, and how often. Try sorting a copy.

Hint 2

Go through the values from smallest to largest. To beat a value, which of the unused numbers is the least wasteful one to spend on it?

Hint 3

Think about the value that appears most often, say m times. Every win is either won by a number bigger than it, or won against a number smaller than it. How many wins does that leave at most?

FAQ

What is the best time complexity for Maximize Greatness of an Array?

Optimal (n minus the highest frequency) runs in O(n) time and O(n) extra space. One pass, with constant expected work per number in the hash map.

Which pattern does Maximize Greatness of an Array use?

It is a arrays & hashing problem that uses the greedy pattern. Other problems with the same pattern: Integer to Roman, Jump Game II, Jump Game.

Is there a brute force solution for Maximize Greatness of an Array?

Yes. Brute force (greedy matching with a used array) takes O(n^2) time and O(n) space. Sort a copy of the values.

Which edge cases should I test for Maximize Greatness of an Array?

A single element: it can only sit on itself, so the answer is 0; All values equal: the answer is 0; All values distinct: everything except the largest can be beaten, so the answer is n - 1; Many copies of the smallest value, or of the largest value: the most frequent value decides the answer wherever it sits; Already sorted or reverse sorted input: the order of nums never matters, only the multiset of values; Zeros are allowed: 0 can beat nothing, but anything positive beats it.