2592. Maximize Greatness of an Array LeetCode Solution

In this guide, you will get 2592. Maximize Greatness of an Array LeetCode Solution with the best time and space complexity. The solution to Maximize Greatness of an Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Maximize Greatness of an Array solution in C++
  4. Maximize Greatness of an Array solution in Java
  5. Maximize Greatness of an Array solution in Python
  6. Additional Resources
2592. Maximize Greatness of an Array LeetCode Solution image

Problem Statement of Maximize Greatness of an Array

You are given a 0-indexed integer array nums. You are allowed to permute nums into a new array perm of your choosing.
We define the greatness of nums be the number of indices 0 <= i nums[i].
Return the maximum possible greatness you can achieve after permuting nums.

Example 1:

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].
At indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we return 4.
Example 2:

Input: nums = [1,2,3,4]
Output: 3
Explanation: We can prove the optimal perm is [2,3,4,1].
At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3.

Constraints:

1 <= nums.length <= 105
0 <= nums[i] <= 109

Complexity Analysis

  • Time Complexity: O(\texttt{sort})
  • Space Complexity: O(\texttt{sort})

2592. Maximize Greatness of an Array LeetCode Solution in C++

class Solution {
 public:
  int maximizeGreatness(vector<int>& nums) {
    int ans = 0;

    ranges::sort(nums);

    for (const int num : nums)
      if (num > nums[ans])
        ++ans;

    return ans;
  }
};
/* code provided by PROGIEZ */

2592. Maximize Greatness of an Array LeetCode Solution in Java

class Solution {
  public int maximizeGreatness(int[] nums) {
    int ans = 0;

    Arrays.sort(nums);

    for (final int num : nums)
      if (num > nums[ans])
        ++ans;

    return ans;
  }
}
// code provided by PROGIEZ

2592. Maximize Greatness of an Array LeetCode Solution in Python

class Solution:
  def maximizeGreatness(self, nums: list[int]) -> int:
    ans = 0

    nums.sort()

    for num in nums:
      if num > nums[ans]:
        ans += 1

    return ans
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.