Problem Description
Given a 1-indexed array nums, the goal is to select a "complete subset" of indices such that for every pair of selected indices i and j, the product i * j is a perfect square. Return the sum of the selected elements (from nums) corresponding to a complete subset that has the maximum sum.
A key observation is that if every pair (i, j) in the subset must yield a perfect square when multiplied, then the indices in the subset must share a common property. In fact, by decomposing each index i into i = (square part) * (square-free part), one can show that i * j is a perfect square if and only if the square-free parts of i and j are identical. Therefore, the problem reduces to grouping indices by their square-free parts and summing the corresponding nums values; the answer is the maximum sum over all such groups.
Key Insights
- Each index i can be represented as i = s² * r, where r is square-free.
- For any two indices i and j, i * j is a perfect square if and only if their square-free parts are the same.
- Thus, valid complete subsets correspond exactly to indices that share the same square-free part.
- The solution is to group indices by their square-free part and choose the group with the maximum element sum.
Space and Time Complexity
Time Complexity: O(n * √n) in worst-case (n <= 10⁴, with each index factorized in O(√i) time). Space Complexity: O(n) for storing the grouping and intermediate results.
Solution
The approach involves:
- For each index from 1 to n (remembering that nums is 1-indexed), compute its square-free part. This can be done by checking for each prime factor up to √i and dividing out perfect square factors.
- Create a mapping from the square-free part to the cumulative sum of the corresponding nums values.
- Return the maximum sum among these groups.
To implement these steps, the code leverages a simple factorization procedure (suitable since n is at most 10⁴) and hash table/dictionary to group the sums.