LeetCode 题解工作台
完全子集的最大元素和
给你一个下标从 1 开始、由 n 个整数组成的数组。你需要从 nums 选择一个 完全集 ,其中每对元素下标的乘积都是一个 完全平方数 ,例如选择 a i 和 a j , i * j 一定是完全平方数。 返回 完全子集 所能取到的 最大元素和 。 示例 1: 输入: nums = [8,7,3,5,…
3
题型
5
代码语言
3
相关题
当前训练重点
困难 · 数组·数学
答案摘要
我们注意到,如果一个数字可以表示成 $k \times j^2$ 的形式,那么所有该形式的数字的 是相同的。 因此,我们可以在 范围内枚举 ,然后从 开始枚举 ,每一次累加 $nums[k \times j^2 - 1]$ 的值到 中,直到 $k \times j^2 > n$。此时更新答案为 $ans = \max(ans, t)$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个下标从 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 <= 1041 <= nums[i] <= 109
解题思路
方法一:枚举
我们注意到,如果一个数字可以表示成 的形式,那么所有该形式的数字的 是相同的。
因此,我们可以在 范围内枚举 ,然后从 开始枚举 ,每一次累加 的值到 中,直到 。此时更新答案为 。
最后返回答案 即可。
时间复杂度 ,其中 是数组的长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.