Find the Maximum Number of Elements in Subset - Problem

You are given an array of positive integers nums. You need to select a subset of nums which satisfies the following condition:

You can place the selected elements in a 0-indexed array such that it follows the 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.

Note: The pattern forms a symmetric sequence where powers increase to the middle then decrease.

Examples of valid patterns:

  • [2, 4, 16, 4, 2] follows the pattern (x=2, k=4)
  • [3, 9, 3] follows the pattern (x=3, k=2)
  • [5] follows the pattern (x=5, k=0)

Invalid pattern: [2, 4, 8, 4, 2] does not follow the pattern because 8 ≠ 2⁴

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

Input & Output

Example 1 — Valid Symmetric Pattern
$ Input: nums = [2,4,16,4,2]
Output: 5
💡 Note: All elements can form pattern [2,4,16,4,2] where x=2, powers are [2¹,2²,2⁴,2²,2¹] - perfectly symmetric
Example 2 — Multiple Options
$ Input: nums = [2,4,8,16]
Output: 3
💡 Note: Can form [2,4,2] using x=2 (length 3) or [4,16,4] using x=4 (length 3). Cannot use 8 as 8≠2⁴
Example 3 — Single Element
$ Input: nums = [5]
Output: 1
💡 Note: Pattern [5] with x=5, k=0 is valid - single element always forms valid pattern

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Find Maximum Symmetric Power SubsetInput Array[2, 4, 16, 4, 2]2416422⁴Symmetric Pattern: x=2, k=4Powers increase to middle, then decrease symmetricallyValid SubsetLength = 5Maximum Length: 5All elements form perfect symmetric power pattern
Understanding the Visualization
1
Input Array
Array of positive integers [2,4,16,4,2]
2
Pattern Recognition
Find symmetric power sequences: [x, x², x⁴, x², x]
3
Maximum Length
Return length of longest valid symmetric subset
Key Takeaway
🎯 Key Insight: Valid subsets must form symmetric patterns where elements follow power sequences of a base number
Asked in
Google 25 Meta 18 Amazon 15
26.8K Views
Medium Frequency
~25 min Avg. Time
892 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