Input: nums =[1000000000,1000000000]Output: 2Explanation:
Since both numbers are equal, they cannot be removed.#### Example 4Input: nums =[2,3,4,4,4]Output: 1Explanation:

To minimize the array length, we want to remove as many pairs as possible where nums[i] < nums[j]. Since the array is sorted, we can use two pointers: one starting from the left and one from the right, and greedily pair the smallest with the largest possible.
classSolution {
public:int minLengthAfterRemovals(vector<int>& nums) {
int n = nums.size(), left =0, right = n-1, pairs =0;
while (left < right) {
if (nums[left] < nums[right]) {
pairs++;
left++;
right--;
} else {
right--;
}
}
return n -2* pairs;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
funcminLengthAfterRemovals(nums []int) int {
n, left, right, pairs:= len(nums), 0, len(nums)-1, 0forleft < right {
ifnums[left] < nums[right] {
pairs++left++right-- } else {
right-- }
}
returnn-2*pairs}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintminLengthAfterRemovals(int[] nums) {
int n = nums.length, left = 0, right = n-1, pairs = 0;
while (left < right) {
if (nums[left]< nums[right]) {
pairs++;
left++;
right--;
} else {
right--;
}
}
return n - 2 * pairs;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funminLengthAfterRemovals(nums: IntArray): Int {
var left = 0var right = nums.size - 1var pairs = 0while (left < right) {
if (nums[left] < nums[right]) {
pairs++ left++ right-- } else {
right-- }
}
return nums.size - 2 * pairs
}
}
1
2
3
4
5
6
7
8
9
10
11
12
defmin_length_after_removals(nums: list[int]) -> int:
n = len(nums)
left, right =0, n-1 pairs =0while left < right:
if nums[left] < nums[right]:
pairs +=1 left +=1 right -=1else:
right -=1return n -2* pairs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnmin_length_after_removals(nums: Vec<i32>) -> i32 {
let n = nums.len();
let (mut left, mut right, mut pairs) = (0, n-1, 0);
while left < right {
if nums[left] < nums[right] {
pairs +=1;
left +=1;
right -=1;
} else {
right -=1;
}
}
(n -2* pairs) asi32 }
}