Imagine you have an array of numbers, and you want to create the most impressive rearrangement possible! You're given a 0-indexed integer array nums, and you can permute (rearrange) it into any order you want to create a new array perm.
The greatness of your arrangement is defined as the number of positions where perm[i] > nums[i] - essentially, how many elements in your rearranged array are greater than the corresponding elements in the original array.
Goal: Return the maximum possible greatness you can achieve by optimally rearranging the array.
Example: If nums = [1,3,5,2,1,3,1], you could rearrange it to perm = [3,5,1,3,2,1,1]. Comparing position by position: 3>1 ✓, 5>3 ✓, 1>5 ✗, 3>2 ✓, 2>1 ✓, 1>3 ✗, 1>1 ✗. That gives us a greatness of 4!
Input & Output
Visualization
Time & Space Complexity
Sorting both arrays takes O(n log n), then single pass with two pointers takes O(n)
Need extra space to store the sorted copy of the array
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] ≤ 109
- The array can contain duplicate elements