Find the Maximum Number of Elements in Subset - Problem

You are given an array of positive integers nums. Your task is to select a subset of these numbers to form a symmetric mountain pattern following a very specific rule.

The selected elements must be arrangeable in a 0-indexed array that follows this pattern:

[x, x², x⁴, ..., x^(k/2), x^k, x^(k/2), ..., x⁴, x², x]

Where k can be any non-negative power of 2 (0, 2, 4, 8, 16, ...).

Examples of valid patterns:

  • [2, 4, 16, 4, 2] ✅ (x=2, k=4: 2¹, 2², 2⁴, 2², 2¹)
  • [3, 9, 3] ✅ (x=3, k=2: 3¹, 3², 3¹)
  • [5] ✅ (x=5, k=0: just 5⁰ which is conceptually 5¹)

Invalid pattern:

  • [2, 4, 8, 4, 2] ❌ (k=3 is not a power of 2)

Return the maximum number of elements in a subset that satisfies these conditions.

Input & Output

Time & Space Complexity

Time Complexity
⏱️
O(n + k×log(max_val))

O(n) to build frequency map, O(k×log(max_val)) where k is unique values and log factor comes from checking power chains

n
2n
Linearithmic
Space Complexity
O(k)

Hash table stores at most k unique values from input array

n
2n
Linear Space

Constraints

Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen