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 INPUT 1-indexed array nums: i=1 8 i=2 7 i=3 3 i=4 5 i=5 7 i=6 2 i=7 4 i=8 9 Constraint: For any pair (i, j) in subset: i * j = perfect square Valid index pairs: 1*1=1, 1*4=4, 4*9=36 (all perfect squares) Input Array: [8,7,3,5,7,2,4,9] ALGORITHM STEPS 1 Group by Square-Free Part Index i belongs to group k if i = k * m^2 for some m 2 Identify Groups Group 1: indices 1,4 Group 2: indices 2,8 Group 3: index 3 3 Calculate Group Sums G1: nums[1]+nums[4]=8+5=13 G2: nums[2]+nums[8]=7+9=16 G3: nums[3]=3 4 Find Maximum Sum Compare all group sums max(13, 16, 3, ...) = 16 Group Summary: G1:{1,4}-->8+5=13 G2:{2,8}-->7+9=16 [MAX] FINAL RESULT Best Complete Subset Found: Group 2 (k=2) Indices: {2, 8} Values: nums[2]=7, nums[8]=9 Verification: 2 * 8 = 16 = 4^2 [OK] Sum Calculation: 7 + 9 = 16 Output: 16 [OK] Maximum sum achieved Key Insight: Indices i and j multiply to a perfect square iff they have the same "square-free part". For each k from 1 to n, indices {k, 4k, 9k, 16k, ...} form a valid complete subset. We iterate through each group, compute the sum, and track the maximum. Time: O(n*sqrt(n)) TutorialsPoint - Maximum Element-Sum of a Complete Subset of Indices | Mathematical Grouping Approach
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