g2501_2600.s2592_maximize_greatness_of_an_array.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g2501_2600.s2592_maximize_greatness_of_an_array;
// #Medium #Array #Sorting #Greedy #Two_Pointers
// #2023_08_23_Time_8_ms_(100.00%)_Space_57.2_MB_(41.49%)
import java.util.Arrays;
/**
* 2592 - Maximize Greatness of an Array\.
*
* Medium
*
* 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` 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`.
*
* **Example 1:**
*
* **Input:** nums = [1,3,5,2,1,3,1]
*
* **Output:** 4
*
* **Explanation:** 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 return 4.
*
* **Example 2:**
*
* **Input:** nums = [1,2,3,4]
*
* **Output:** 3
*
* **Explanation:** We can prove the optimal perm is [2,3,4,1]. At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3.
*
* **Constraints:**
*
* * 1 <= nums.length <= 105
* * 0 <= nums[i] <= 109
**/
public class Solution {
public int maximizeGreatness(int[] nums) {
Arrays.sort(nums);
int perm = 0;
for (int num : nums) {
if (nums[perm] < num) {
perm++;
}
}
return perm;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy