MediumNo. 2592

Maximize Greatness of an Array — LeetCode 2592 Python Solution

Topics
Greedy, Array, Two Pointers, Sorting
Reading time
2 min

The problem

You are given a 0-indexed integer array nums. You are allowed to permute nums into a new array perm of your choosing.

Example

Input
nums = [1,3,5,2,1,3,1]
Output
4
Explanation
One of the optimal rearrangements is perm = [2,5,1,3,3,1,1].

Python solution

PythonSolution
class Solution:
    def maximizeGreatness(self, nums: List[int]) -> int:
        nums.sort()
        i = 0
        for x in nums:
            i += x > nums[i]
        return i

Complexity

Time
O(n × log n)
Space · auxiliary
O(log n)where n is the length of the array nums

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2592. Maximize Greatness of an Array is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0455Assign CookiesEasy
0611Valid Triangle NumberMedium
0826Most Profit Assigning WorkMedium
0870Advantage ShuffleMedium
0881Boats to Save PeopleMedium
0948Bag of TokensMedium

Frequently asked questions

How hard is LeetCode 2592. Maximize Greatness of an Array?

LeetCode 2592. Maximize Greatness of an Array is rated Medium on LeetCode.

What is the time complexity of LeetCode 2592. Maximize Greatness of an Array?

The Python solution on this page runs in O(n × log n).

What is the space complexity of LeetCode 2592. Maximize Greatness of an Array?

The Python solution on this page uses O(log n), where n is the length of the array nums auxiliary space.

What topics does LeetCode 2592. Maximize Greatness of an Array cover?

LeetCode 2592. Maximize Greatness of an Array is tagged Greedy, Array, Two Pointers and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.