Maximize Greatness of an Array — LeetCode 2592 Python Solution

MediumGreedyArrayTwo PointersSorting
Problem
#2592
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

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

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n), where n is the length of the array nums auxiliary

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

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 \times \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.

Get Stealth Interview