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 Elements in Subset INPUT nums = [2, 4, 16, 4, 2] 2 4 16 4 2 [0] [1] [2] [3] [4] Required Pattern: [x, x^2, x^4, ..., x^k, ..., x^4, x^2, x] Palindromic powers of x Frequency Count: 2: 2 times 4: 2 times 16: 1 time ALGORITHM STEPS 1 Count Frequencies Use HashMap to count occurrences of each num 2 Start from x=2 Chain: 2 --> 4 --> 16 Check pairs exist 3 Build Sequence For each x, extend chain while pairs available 4 Track Maximum Length = 2*depth + 1 (palindrome structure) Chain Building: 2 --> 4 --> 16 --> 4 --> 2 2^1, 2^2, 2^4, 2^2, 2^1 Depth=2, Length=5 FINAL RESULT Maximum Subset Found: 2 4 16 4 2 x x^2 x^4 x^2 x Output: 5 OK - Valid Subset! Verification: x = 2 (base) Pattern: [2,4,16,4,2] = [2^1,2^2,2^4,2^2,2^1] Palindromic: OK Count = 5 elements Key Insight: The subset must form a palindromic sequence of powers: [x, x^2, x^4, ..., x^k, ..., x^4, x^2, x]. Use a HashMap to count frequencies, then greedily build chains from smallest base values. Each pair (except peak) needs 2 occurrences. The middle element (x^k) needs only 1. Time: O(n log M) TutorialsPoint - Find the Maximum Number of Elements in Subset | Optimal Solution
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