Maximum Element-Sum of a Complete Subset of Indices - Problem

You are given a 1-indexed array nums of positive integers. Your task is to select a complete subset from nums where every pair of selected indices when multiplied together results in a perfect square.

More formally, if you select indices i and j, then i * j must be a perfect square.

Return the sum of the complete subset with the maximum sum.

Input & Output

Example 1 — Basic Case
$ Input: nums = [8,7,3,5,7,2,4,9]
Output: 16
💡 Note: Indices 2 and 8 have square-free part 2, so 2×8=16 is a perfect square. Their values are 7+9=16, which is the maximum.
Example 2 — Single Element
$ Input: nums = [5]
Output: 5
💡 Note: Only one element, so the subset contains just index 1 with value 5.
Example 3 — Multiple Groups
$ Input: nums = [1,4,3,3,2]
Output: 6
💡 Note: Indices 3 and 4 both have square-free part 3, values 3+3=6. Index 1 has square-free 1 (value 1), index 2 has square-free 2 (value 4), index 5 has square-free 5 (value 2).

Constraints

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

Visualization

Tap to expand
Maximum Element-Sum of Complete Subset: nums=[8,7,3,5,7,2,4,9]87357249i=1i=2i=3i=4i=5i=6i=7i=8Find indices where i×j is perfect squareIndices 2 and 8: 2×8 = 16 = 4² ✓Both have square-free part = 2Complete Subset: {2, 8}Sum = 7 + 9 = 16Maximum Sum: 16
Understanding the Visualization
1
Input
Array nums=[8,7,3,5,7,2,4,9] with 1-indexed positions
2
Process
Group indices by square-free parts: same square-free → compatible
3
Output
Maximum sum is 16 from indices 2,8 (values 7,9)
Key Takeaway
🎯 Key Insight: Two indices can be in the same complete subset if they have identical square-free parts
Asked in
Google 15 Meta 8
12.5K Views
Medium Frequency
~35 min Avg. Time
234 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