Maximize Greatness of an Array - Problem

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 to be the number of indices 0 <= i < nums.length for which perm[i] > nums[i].

Return the maximum possible greatness you can achieve after permuting nums.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,5,2,4]
Output: 3
💡 Note: Optimal permutation is [2,4,5,3,1]. Comparing with original [1,3,5,2,4]: positions 0 (2>1), 1 (4>3), and 3 (3>2) satisfy perm[i] > nums[i], giving greatness = 3.
Example 2 — All Same Elements
$ Input: nums = [1,1,1,1]
Output: 0
💡 Note: All elements are identical, so no matter how we permute, perm[i] can never be greater than nums[i]. Maximum greatness = 0.
Example 3 — Ascending Order
$ Input: nums = [1,2,3,4,5]
Output: 4
💡 Note: Optimal permutation is [2,3,4,5,1]. This gives us 4 positions where perm[i] > nums[i]: 2>1, 3>2, 4>3, 5>4.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Maximize Greatness: Find Best PermutationOriginal Array:13524Optimal Permutation:24531Comparison:2 > 1 ✓4 > 3 ✓5 = 5 ✗3 > 2 ✓1 < 4 ✗Key Strategy1. Sort the array: [1,2,3,4,5]2. Use two pointers to greedily match each element with smallest larger oneMaximum Greatness3
Understanding the Visualization
1
Input
Given array [1,3,5,2,4]
2
Process
Find optimal permutation using greedy matching
3
Output
Maximum greatness count = 3
Key Takeaway
🎯 Key Insight: Sort the array and greedily match each element with the smallest available larger element to maximize greatness count.
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen