Input: nums =[1,3,5,2,1,3,1]Output: 4Explanation: 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 return4.
To maximize the number of indices where perm[i] > nums[i], we want to match each number in nums with the smallest possible greater number from the permuted array. By sorting the array and using two pointers, we can greedily pair each number with the next greater number.
classSolution {
public:int maximizeGreatness(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size(), ans =0, i =0, j =0;
while (i < n && j < n) {
if (nums[j] > nums[i]) {
ans++;
i++;
}
j++;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcmaximizeGreatness(nums []int) int {
sort.Ints(nums)
n, ans, i, j:= len(nums), 0, 0, 0fori < n&&j < n {
ifnums[j] > nums[i] {
ans++i++ }
j++ }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintmaximizeGreatness(int[] nums) {
Arrays.sort(nums);
int n = nums.length, ans = 0, i = 0, j = 0;
while (i < n && j < n) {
if (nums[j]> nums[i]) {
ans++;
i++;
}
j++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funmaximizeGreatness(nums: IntArray): Int {
nums.sort()
var ans = 0var i = 0var j = 0while (i < nums.size && j < nums.size) {
if (nums[j] > nums[i]) {
ans++ i++ }
j++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defmaximizeGreatness(self, nums: list[int]) -> int:
nums.sort()
n = len(nums)
ans = i = j =0while i < n and j < n:
if nums[j] > nums[i]:
ans +=1 i +=1 j +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnmaximize_greatness(mut nums: Vec<i32>) -> i32 {
nums.sort();
let n = nums.len();
let (mut ans, mut i, mut j) = (0, 0, 0);
while i < n && j < n {
if nums[j] > nums[i] {
ans +=1;
i +=1;
}
j +=1;
}
ans asi32 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
maximizeGreatness(nums: number[]):number {
nums.sort((a, b) =>a-b);
letn=nums.length, ans=0, i=0, j=0;
while (i<n&&j<n) {
if (nums[j] >nums[i]) {
ans++;
i++;
}
j++;
}
returnans;
}
}