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 of an Array INPUT Original Array: nums 1 3 5 2 4 i=0 i=1 i=2 i=3 i=4 Goal: Find permutation perm where perm[i] > nums[i] for maximum indices Input: [1, 3, 5, 2, 4] Length: 5 elements Sorted: [1, 2, 3, 4, 5] for greedy approach ALGORITHM STEPS 1 Sort Both Arrays Sort nums and create sorted copy for perm 2 Two Pointer Setup i=0 for nums (target) j=0 for perm (candidate) 3 Greedy Matching If perm[j] > nums[i]: count++, move both Else: move j only 4 Count Matches Return total count of successful pairs Sorted: [1,2,3,4,5] 1-->2 OK 2-->3 OK 3-->4 OK 4-->5 skip 5-->none FINAL RESULT Optimal Permutation: 2 4 1 3 5 Comparison with nums: nums[0]=1, perm[0]=2: 2>1 OK nums[1]=3, perm[1]=4: 4>3 OK nums[2]=5, perm[2]=1: 1<5 NO nums[3]=2, perm[3]=3: 3>2 OK nums[4]=4, perm[4]=5: 5>4 OK (3 successful matches) Output: 3 Maximum Greatness = 3 Key Insight: The greedy approach works by sorting both arrays and matching each element with the smallest element that is strictly greater than it. This ensures we don't "waste" larger elements on smaller targets, maximizing the total count. Time complexity: O(n log n) for sorting. TutorialsPoint - Maximize Greatness of an Array | Greedy Approach
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