Input: nums =[3,5,2,4]Output: 2Explanation: In the first operation: pick i =2 and j =1, the operation is allowed because 2* nums[2]<= nums[1]. Then mark index 2 and 1.It can be shown that there's no other valid operation so the answer is2.
Input: nums =[9,2,5,4]Output: 4Explanation: In the first operation: pick i =3 and j =0, the operation is allowed because 2* nums[3]<= nums[0]. Then mark index 3 and 0.In the second operation: pick i =1 and j =2, the operation is allowed because 2* nums[1]<= nums[2]. Then mark index 1 and 2.Since there is no other operation, the answer is4.
To maximize the number of marked indices, we want to pair the smallest numbers with the largest numbers such that 2 * nums[i] <= nums[j]. Sorting the array allows us to efficiently pair the smallest available numbers with the largest possible partners using two pointers.
classSolution {
public:int maxNumOfMarkedIndices(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size(), l =0, r = n/2, ans =0;
while(l < n/2&& r < n) {
if(2* nums[l] <= nums[r]) {
ans +=2;
++l; ++r;
} else {
++r;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
funcmaxNumOfMarkedIndices(nums []int) int {
sort.Ints(nums)
n, l, r, ans:= len(nums), 0, len(nums)/2, 0forl < n/2&&r < n {
if2*nums[l] <=nums[r] {
ans+=2l++r++ } else {
r++ }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintmaxNumOfMarkedIndices(int[] nums) {
Arrays.sort(nums);
int n = nums.length, l = 0, r = n/2, ans = 0;
while(l < n/2 && r < n) {
if(2 * nums[l]<= nums[r]) {
ans += 2;
l++;
r++;
} else {
r++;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funmaxNumOfMarkedIndices(nums: IntArray): Int {
nums.sort()
val n = nums.size
var l = 0; var r = n/2; var ans = 0while(l < n/2&& r < n) {
if(2 * nums[l] <= nums[r]) {
ans +=2 l++ r++ } else {
r++ }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defmaxNumOfMarkedIndices(self, nums: list[int]) -> int:
nums.sort()
n = len(nums)
l, r, ans =0, n//2, 0while l < n//2and r < n:
if2* nums[l] <= nums[r]:
ans +=2 l +=1 r +=1else:
r +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnmax_num_of_marked_indices(mut nums: Vec<i32>) -> i32 {
nums.sort();
let n = nums.len();
let (mut l, mut r, mut ans) = (0, n/2, 0);
while l < n/2&& r < n {
if2*nums[l] <= nums[r] {
ans +=2;
l +=1;
r +=1;
} else {
r +=1;
}
}
ans asi32 }
}