LeetCode 题解工作台

完全子集的最大元素和

给你一个下标从 1 开始、由 n 个整数组成的数组。你需要从 nums 选择一个 完全集 ,其中每对元素下标的乘积都是一个 完全平方数 ,例如选择 a i 和 a j , i * j 一定是完全平方数。 返回 完全子集 所能取到的 最大元素和 。 示例 1: 输入: nums = [8,7,3,5,…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

困难 · 数组·数学

bolt

答案摘要

我们注意到,如果一个数字可以表示成 $k \times j^2$ 的形式,那么所有该形式的数字的 是相同的。 因此,我们可以在 范围内枚举 ,然后从 开始枚举 ,每一次累加 $nums[k \times j^2 - 1]$ 的值到 中,直到 $k \times j^2 > n$。此时更新答案为 $ans = \max(ans, t)$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 1 开始、由 n 个整数组成的数组。你需要从 nums 选择一个 完全集,其中每对元素下标的乘积都是一个 完全平方数,例如选择 ai 和 aj ,i * j 一定是完全平方数。

返回 完全子集 所能取到的 最大元素和

 

示例 1:

输入:nums = [8,7,3,5,7,2,4,9]

输出:16

解释:

我们选择下标为 2 和 8 的元素,并且 2 * 8 是一个完全平方数。

示例 2:

输入:nums = [8,10,3,8,1,13,7,9,4]

输出:20

解释:

我们选择下标为 1, 4, 9 的元素。1 * 4, 1 * 9, 4 * 9 是完全平方数。

 

提示:

  • 1 <= n == nums.length <= 104
  • 1 <= nums[i] <= 109
lightbulb

解题思路

方法一:枚举

我们注意到,如果一个数字可以表示成 k×j2k \times j^2 的形式,那么所有该形式的数字的 kk 是相同的。

因此,我们可以在 [1,..n][1,..n] 范围内枚举 kk,然后从 11 开始枚举 jj,每一次累加 nums[k×j21]nums[k \times j^2 - 1] 的值到 tt 中,直到 k×j2>nk \times j^2 > n。此时更新答案为 ans=max(ans,t)ans = \max(ans, t)

最后返回答案 ansans 即可。

时间复杂度 O(n)O(n),其中 nn 是数组的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for understanding of prime factorization and perfect square properties.

  • question_mark

    Check if the candidate can apply number theory efficiently in subset problems.

  • question_mark

    Evaluate the ability to optimize solutions with dynamic programming or other techniques.

warning

常见陷阱

外企场景
  • error

    Overlooking the importance of prime factorization for identifying perfect square pairs.

  • error

    Failing to optimize the solution for large input sizes (n up to 10^4).

  • error

    Choosing a brute force approach without considering number theory for efficiency.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Extend the problem by finding the subset with the minimum sum instead of the maximum sum.

  • arrow_right_alt

    Consider a variant where the perfect square condition is replaced with a different mathematical property (e.g., perfect cube).

  • arrow_right_alt

    Modify the problem to allow subsets that are not necessarily contiguous but still respect the perfect square condition.

help

常见问题

外企场景

完全子集的最大元素和题解:数组·数学 | LeetCode #2862 困难