子数组的最大 GCD-Sum
难度:
标签:
题目描述
代码结果
运行时间: 1219 ms, 内存: 25.6 MB
/*
* Leetcode Problem 2941: Maximum GCD-Sum of Subarray
*
* Problem Description:
* Given an array of positive integers, find the maximum sum of any subarray such that the GCD (Greatest Common Divisor) of the elements in the subarray is greater than 1.
*
* Solution Approach using Java Streams:
* 1. Generate all possible subarrays using IntStream.
* 2. For each subarray, calculate the GCD using reduce method.
* 3. Filter subarrays with GCD greater than 1 and calculate their sum.
* 4. Track the maximum sum among all valid subarrays.
*/
import java.util.stream.IntStream;
public class MaximumGCDSubarraySumStream {
// Helper method to compute the GCD of two numbers
private static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static int maxGCDSum(int[] nums) {
return IntStream.range(0, nums.length)
.flatMap(i -> IntStream.rangeClosed(i, nums.length - 1)
.mapToObj(j -> IntStream.rangeClosed(i, j).map(k -> nums[k]).toArray())
.filter(subarray -> IntStream.of(subarray).reduce(nums[i], MaximumGCDSubarraySumStream::gcd) > 1)
.mapToInt(subarray -> IntStream.of(subarray).sum())
)
.max()
.orElse(0);
}
public static void main(String[] args) {
int[] nums = {3, 6, 9, 15};
System.out.println(maxGCDSum(nums)); // Output: 33
}
}
解释
方法:
此题解采用了动态规划和哈希表的混合策略来解决问题。基本思路是通过遍历数组,持续更新以每个元素为结尾的子数组的最大GCD和其对应的和与长度。使用哈希表来存储当前所有可能的GCD值及其对应的最大和与子数组长度。对于每个新的元素x,更新哈希表,检查与之前每个子数组的最大公约数,并更新这些公约数的最大和与长度。如果达到子数组长度k,计算可能的答案。这种方法确保了我们能够找到长度至少为k的子数组的最大GCD-Sum。
时间复杂度:
O(n^2)
空间复杂度:
O(n)
代码细节讲解
🦆
在算法中,为什么要单独处理`k为1`的情况,直接返回最大元素的平方?
▷🦆
算法中使用的`gcd`函数是如何确保在更新哈希表时保持计算效率的?
▷🦆
在更新哈希表时,如何决定是否创建新的GCD键或更新现有键的值?
▷🦆
对于每个GCD键的值,您选择存储最大和与子数组长度,这种选择的优点是什么?
▷