完全子集的最大元素和
难度:
标签:
题目描述
You are given a 1-indexed array nums
of n
integers.
A set of numbers is complete if the product of every pair of its elements is a perfect square.
For a subset of the indices set {1, 2, ..., n}
represented as {i1, i2, ..., ik}
, we define its element-sum as: nums[i1] + nums[i2] + ... + nums[ik]
.
Return the maximum element-sum of a complete subset of the indices set {1, 2, ..., n}
.
A perfect square is a number that can be expressed as the product of an integer by itself.
Example 1:
Input: nums = [8,7,3,5,7,2,4,9] Output: 16 Explanation: Apart from the subsets consisting of a single index, there are two other complete subsets of indices: {1,4} and {2,8}. The sum of the elements corresponding to indices 1 and 4 is equal to nums[1] + nums[4] = 8 + 5 = 13. The sum of the elements corresponding to indices 2 and 8 is equal to nums[2] + nums[8] = 7 + 9 = 16. Hence, the maximum element-sum of a complete subset of indices is 16.
Example 2:
Input: nums = [5,10,3,10,1,13,7,9,4] Output: 19 Explanation: Apart from the subsets consisting of a single index, there are four other complete subsets of indices: {1,4}, {1,9}, {2,8}, {4,9}, and {1,4,9}. The sum of the elements corresponding to indices 1 and 4 is equal to nums[1] + nums[4] = 5 + 10 = 15. The sum of the elements corresponding to indices 1 and 9 is equal to nums[1] + nums[9] = 5 + 4 = 9. The sum of the elements corresponding to indices 2 and 8 is equal to nums[2] + nums[8] = 10 + 9 = 19. The sum of the elements corresponding to indices 4 and 9 is equal to nums[4] + nums[9] = 10 + 4 = 14. The sum of the elements corresponding to indices 1, 4, and 9 is equal to nums[1] + nums[4] + nums[9] = 5 + 10 + 4 = 19. Hence, the maximum element-sum of a complete subset of indices is 19.
Constraints:
1 <= n == nums.length <= 104
1 <= nums[i] <= 109
代码结果
运行时间: 52 ms, 内存: 17.4 MB
/*
思路:
1. 我们使用Java Stream API来实现相同的逻辑。
2. 遍历数组,检查每一对元素是否是完全平方数。
3. 计算每个完全子集的元素和,最后返回最大值。
*/
import java.util.Arrays;
public class Solution {
public int maxSumOfCompleteSubsets(int[] nums) {
return Arrays.stream(nums)
.flatMap(i -> Arrays.stream(nums)
.filter(j -> i != j && isPerfectSquare(i * j))
.map(j -> i + j))
.max()
.orElse(0);
}
private boolean isPerfectSquare(int num) {
int sqrt = (int) Math.sqrt(num);
return sqrt * sqrt == num;
}
}
解释
方法:
此题解的核心思想是通过预计算每个数的“核心”值,该核心值是除去所有平方因子后剩下的部分。例如,对于数字12,其分解为2^2 * 3,去掉平方因子2^2后,剩下的核心值是3。这样,任何两个数如果它们的核心值相同,那么这两个数的乘积就是一个完全平方数。这是因为它们各自的非平方部分相乘后,剩下的就只有平方因子的乘积,仍然是一个完全平方数。\n解决方案中首先预处理一个数组`core`,其中`core[i]`表示数字`i`的核心值。然后,遍历给定数组`nums`,用一个数组`s`来记录每个核心值对应的元素之和。最后,返回`s`数组中的最大值,这就是所有可能的完全子集中的最大元素和。
时间复杂度:
O(n*sqrt(n))
空间复杂度:
O(n)
代码细节讲解
🦆
核心值的概念是怎样帮助解决这道题目的,能否详细解释其在算法中的作用?
▷🦆
在预处理core数组时,为什么选择对每个i从1到isqrt(MX // i)进行迭代,这样的范围是怎么确定的?
▷🦆
数组s的索引似乎应该是core[x],而不是core[i],这里的索引是不是有误,如果有误,可能会如何影响程序的输出?
▷🦆
给定数组nums的长度和MX的大小可能不同,这里为什么将s数组的长度设置为len(nums)+1而不是根据核心值的可能数量来设置?
▷