LeetCode 2341: Maximum Number of Pairs in Array Solution

Master LeetCode problem 2341 (Maximum Number of Pairs in Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2341. Maximum Number of Pairs in Array

Problem Explanation

Explanation:

To solve this problem, we need to iterate through the array and count the occurrences of each number. For each number that appears more than once, we can form pairs by pairing them up. The maximum number of pairs that can be formed is half of the total occurrences of each number. We can keep track of the number of pairs formed and the remaining numbers after forming pairs.

  • Initialize a HashMap to store the count of each number in the input array.
  • Iterate through the input array and count the occurrences of each number.
  • For each number that appears more than once, calculate the number of pairs that can be formed.
  • Update the count of pairs and the remaining numbers accordingly.

:

Solution Code

import java.util.*;

class Solution {
    public int[] maxPair(int[] nums) {
        Map<Integer, Integer> count = new HashMap<>();
        int pairs = 0;
        
        for (int num : nums) {
            count.put(num, count.getOrDefault(num, 0) + 1);
            if (count.get(num) == 2) {
                pairs++;
                count.put(num, 0);
            }
        }
        
        int remaining = 0;
        for (int val : count.values()) {
            if (val > 0) {
                remaining++;
            }
        }
        
        return new int[] {pairs, remaining};
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2341 (Maximum Number of Pairs in Array)?

This page provides optimized solutions for LeetCode problem 2341 (Maximum Number of Pairs in Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2341 (Maximum Number of Pairs in Array)?

The time complexity for LeetCode 2341 (Maximum Number of Pairs in Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2341 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2341 in Java, C++, or Python.

Back to LeetCode Solutions