LeetCode solutions

3299. Find the Maximum Number of Elements in Subset

My accepted Python solution to LeetCode problem 3299, Find the Maximum Number of Elements in Subset, running in 122ms.

  • Difficulty: Medium
  • Python
  • Runtime 122ms
  • Memory 29.8MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 122ms, memory 29.8MB, accepted 2025-12-31.

python
class Solution:
    def maximumLength(self, nums: List[int]) -> int:
        from collections import Counter
        cnt = Counter(nums)
        
        ans = cnt[1] if cnt[1] % 2 == 1 else cnt[1] - 1
        
        for x in cnt:
            if x == 1:
                continue
            # Try to build chain x, x^2, x^4, ...
            length = 0
            curr = x
            while curr in cnt:
                if cnt[curr] >= 2:
                    length += 2
                    curr = curr * curr
                else:
                    # cnt[curr] == 1
                    length += 1
                    break
            # If we ended with cnt[curr] >= 2, we need odd length
            if cnt.get(curr, 0) == 0:
                length -= 1
            ans = max(ans, length)
        
        return ans if ans > 0 else 1

Source