Skip to content

Latest commit

 

History

History
98 lines (80 loc) · 2.98 KB

README.md

File metadata and controls

98 lines (80 loc) · 2.98 KB

You are given an integer array nums and an integer k.

In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.

Return the maximum number of operations you can perform on the array.

 

Example 1:

Input: nums = [1,2,3,4], k = 5
Output: 2
Explanation: Starting with nums = [1,2,3,4]:
- Remove numbers 1 and 4, then nums = [2,3]
- Remove numbers 2 and 3, then nums = []
There are no more pairs that sum up to 5, hence a total of 2 operations.

Example 2:

Input: nums = [3,1,3,4,3], k = 6
Output: 1
Explanation: Starting with nums = [3,1,3,4,3]:
- Remove the first two 3's, then nums = [1,4,3]
There are no more pairs that sum up to 6, hence a total of 1 operation.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 1 <= k <= 109

Related Topics:
Array, Hash Table, Two Pointers, Sorting

Similar Questions:

Solution 1.

Save the frequence of numbers in a map m.

For each pair [n, cnt] in m:

  • If k - n == n, add cnt / 2 to answer.
  • Otherwise, add c = min(cnt, m[k - n]) to the answer, and deduct c from m[n] and m[k - n].
// OJ: https://leetcode.com/problems/max-number-of-k-sum-pairs/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    int maxOperations(vector<int>& nums, int k) {
        unordered_map<int, int> m;
        for (int n : nums) m[n]++;
        int ans = 0;
        for (auto [n, cnt] : m) {
            if (k - n == n) ans += cnt / 2;
            else if (m.count(k - n))  {
                int c = min(cnt, m[k - n]);
                ans += c;
                m[n] -= c;
                m[k - n] -= c;
            }
        }
        return ans;
    }
};

Solution 2. Two Pointers

// OJ: https://leetcode.com/problems/max-number-of-k-sum-pairs/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
    int maxOperations(vector<int>& A, int k) {
        sort(begin(A), end(A));
        int i = 0, j = A.size() - 1, ans = 0;
        while (i < j) {
            int sum = A[i] + A[j];
            if (sum == k) ++ans;
            if (sum >= k) --j;
            if (sum <= k) ++i;
        }
        return ans;
    }
};