Skip to content

2341. Maximum Number of Pairs in Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  vector<int> numberOfPairs(vector<int>& nums) {
    constexpr int kMax = 100;
    vector<int> ans(2);
    vector<int> count(kMax + 1);

    for (const int num : nums)
      ++count[num];

    for (int i = 0; i <= kMax; ++i) {
      ans[0] += count[i] / 2;
      ans[1] += count[i] & 1;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int[] numberOfPairs(int[] nums) {
    final int kMax = 100;
    int[] ans = new int[2];
    int[] count = new int[kMax + 1];

    for (final int num : nums)
      ++count[num];

    for (int i = 0; i <= kMax; ++i) {
      ans[0] += count[i] / 2;
      if (count[i] % 2 == 1)
        ++ans[1];
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def numberOfPairs(self, nums: list[int]) -> list[int]:
    ans = [0] * 2
    count = collections.Counter(nums)

    for i in range(101):
      ans[0] += count[i] // 2
      ans[1] += count[i] & 1

    return ans