Record: Lituo Solution: 1679. The maximum number of K and number pairs

Question: You are given an array of integers numsand an integer k. In each step, you need to select ktwo integers whose sum is from the array and move them out of the array. Returns the maximum number of operations you can perform on the array.

Example 1:

Input: nums = [1,2,3,4], k = 5
 Output: 2
 Explanation: At the beginning nums = [1,2,3,4]: 
- shift out 1 and 4, after that nums = [2,3] 
- Move out 2 and 3, after nums = [] 
there is no more pair of numbers that sum to 5, so at most 2 operations are performed.

Example 2:

Input: nums = [3,1,3,4,3], k = 6
 Output: 1
 Explanation: At the beginning nums = [3,1,3,4,3]: 
- shift out first two 3's, after that nums = [1,4,3] 
There are no more pairs that sum to 6, so at most 1 operation is performed.

Idea: double pointer. Sort the entire array, and then use double pointers to calculate the front and rear of the array. If the conditions are met, the front and rear pointers will move one bit each, and the count will be increased by one. If it is smaller than the target value, add 1 to the front pointer and calculate again; if it is greater than the target value, then add -1 to the right pointer and calculate again.

class Solution:
    def maxOperations(self, nums: List[int], k: int) -> int:
        n = len(nums)
        nums.sort()
        res =  0
        l , r = 0 , n - 1
        while l < r:
            if nums[l] + nums[r] == k:
                res += 1
                l += 1
                r -= 1
            elif nums[l] + nums[r] < k:
                l += 1
            else:
                r -= 1
        return res

Guess you like

Origin blog.csdn.net/weixin_45314061/article/details/130449276