[Double pointer] 1679. The maximum number of K and number pairs
problem solving ideas
- use double pointer
- Sort the array first from small to large
- Then set the front and back pointers
- Compare the sum of the numbers of the front and back pointers and compare whether it is the same as k and then move the pointer
class Solution {
public int maxOperations(int[] nums, int k) {
int i = 0;
int j = nums.length - 1;
Arrays.sort(nums);
int count = 0;
while(i < j){
int temp = nums[i] + nums[j];
if(temp == k){
count++;
i++;
j--;
}
else if(temp < k){
i++;
}else if(temp > k){
j--;
}
}
return count;
}
}