Maximum Element-Sum of a Complete Subset of Indices — LeetCode 2862 Python Solution

HardArrayMathNumber Theory
Problem
#2862
Reading time
2 min

The problem

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,.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2862. Maximum Element-Sum of a Complete Subset of Indices is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2862. Maximum Element-Sum of a Complete Subset of Indices?
LeetCode 2862. Maximum Element-Sum of a Complete Subset of Indices is rated Hard on LeetCode.
What is the time complexity of LeetCode 2862. Maximum Element-Sum of a Complete Subset of Indices?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2862. Maximum Element-Sum of a Complete Subset of Indices?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2862. Maximum Element-Sum of a Complete Subset of Indices cover?
LeetCode 2862. Maximum Element-Sum of a Complete Subset of Indices is tagged Array, Math and Number Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview