2341. Maximum Number of Pairs in Array — Daily Problem
Problem
2341. Maximum Number of Pairs in Array
Approach
My Approach
Not sure if it was seeing the word "Easy" that made me go for the optimal solution right away. Actually, ylb's hash table approach is still faster here. Sort the list and check pairs by scanning adjacent equal elements.
Hash Table Approach
After counting with Counter, use a += v // 2 and b += v % 2. For each number x with count v:
- If
v >= 1, we can formv // 2pairs from thexvalues in the array. - Accumulate this count into variable
a.
Code
class Solution:
def numberOfPairs(self, nums: List[int]) -> List[int]:
nums.sort()
ans = [0, len(nums)]
for index in range(1, len(nums)):
if nums[index - 1] == nums[index]:
ans[0] += 1
ans[1] -= 2
nums[index - 1] = nums[index] = -1
return ansclass Solution:
def numberOfPairs(self, nums: List[int]) -> List[int]:
x = Counter(nums)
a = 0
b = 0
for k,v in x.items():
a+=v//2
b+=v%2
return [a,b]贡献者
最近更新
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0
2335. Minimum Amount of Time to Fill Cups — Daily Problem
LeetCode 2335. Minimum Amount of Time to Fill Cups — Greedy approach: always serve the two largest counts first, using sorting or a max-heap; alternatively, a mathematical formula handles edge cases efficiently for developers preparing for interviews.
2490. Circular Sentence
LeetCode 2490. Circular Sentence — Check if a sentence is circular by splitting into words and verifying each word's last character matches the next word's first character, wrapping around. For beginners.