Maximum Element-Sum of a Complete Subset of Indices Problem
Description
LeetCode Problem 2862.
You are given a 1-indexed array nums. Your task is to select a complete subset from nums where every pair of selected indices multiplied is a perfect square,. i. e. if you select a_i and a_j, i * j must be a perfect square.
Return the sum of the complete subset with the maximum sum.
Example 1:
Input: nums = [8,7,3,5,7,2,4,9]
Output: 16
Explanation:
We select elements at indices 2 and 8 and 2 * 8 is a perfect square.
Example 2:
Input: nums = [8,10,3,8,1,13,7,9,4]
Output: 20
Explanation:
We select elements at indices 1, 4, and 9. 1 * 4, 1 * 9, 4 * 9 are perfect squares.
Constraints:
1 <= n == nums.length <= 10^41 <= nums[i] <= 10^9
Solution
Approach: Enumeration
A set of indices is complete when every pair has a product that is a perfect square. Write each index as k * j^2 with k square-free; two indices have a square product exactly when they share the same k. So the best complete subset is made of all indices of the form k * j^2 for some k.
Enumerate k from 1 to n, sum nums[k * j^2 - 1] for j = 1, 2, ... while k * j^2 <= n, and keep the maximum. A k that is not square-free just repeats a subset already covered by a smaller k, so it does no harm.
Complexity: time O(n) (the inner loops run about sqrt(n / k) times, which sums to O(n)), space O(1).
class Solution:
def maximumSum(self, nums: List[int]) -> int:
n = len(nums)
ans = 0
for k in range(1, n + 1):
t = 0
j = 1
while k * j * j <= n:
t += nums[k * j * j - 1]
j += 1
ans = max(ans, t)
return ans