Problem Description
Given an integer array nums, you can permute it into any new array perm. The greatness of an array is defined as the count of indices i such that perm[i] > nums[i]. Your task is to maximize the greatness by choosing an optimal permutation of nums.
Key Insights
- Sorting the array allows us to view the elements in a natural order.
- Use a two-pointer greedy approach to pair each original element with the smallest available element from the sorted list that is strictly greater.
- The optimal pairing strategy is similar to maximizing wins in a matching game.
- Greedily increment the pair count when a valid pairing (perm[i] > nums[i]) is found.
Space and Time Complexity
Time Complexity: O(n log n), primarily due to sorting. Space Complexity: O(n), for storing the sorted array and additional pointers.
Solution
- Sort the given array nums, which gives a clear ordering of the numbers.
- Use two pointers: one (i) for iterating over the sorted original array, and another (j) for selecting a candidate from the sorted array that might be placed in the perm array.
- If the candidate value (at pointer j) is strictly greater than the current original value (at pointer i), it is a valid match; increment the count and move both pointers.
- If the candidate is not larger, move the candidate pointer j alone.
- Continue until all potential matches are exhausted. The count represents the maximum possible greatness.