【发布时间】:2022-01-14 12:32:02
【问题描述】:
从给定数组的连续子集中找出可能的最大差异之和。
给定一个包含 n 个非负整数(允许重复元素)的数组 arr[],从给定数组的连续子集中找出可能的最大差异之和。
假设 max(s) 表示任何子集“s”中的最大值,而 min(s) 表示集合“s”中的最小值。我们需要找到所有可能子集的 max(s)-min(s) 之和。
Input : arr[] = {1, 2, 3}
Output : result = 4
说明:
All possible subset and for each subset s,
max(s)-min(s) are as :
SUBSET | max(s) | min(s) | max(s)-min(s)
{1, 2} | 2 | 1 | 1
{2, 3} | 3 | 2 | 1
{1, 2, 3} | 3 | 1 | 2
Total Difference sum = 4
Note : max(s) - min(s) for all subset with
single element must be zero.
约束:
Array size can be from 1 to 10 power 5, also each element in array can be from 1 to 10 power 5.
这是取自 here 的代码,但此代码检查所有可能的子集而不是连续的子集:
public static int MOD = 1000000007;
// function for sum of max min difference
public static long maxMin (int arr[], int n)
{
// sort all numbers
Arrays.sort(arr);
// iterate over array and with help of
// horner's rule calc max_sum and min_sum
long min_sum = 0, max_sum = 0;
for (int i = 0; i < n; i++)
{
max_sum = 2 * max_sum + arr[n - 1 - i];
max_sum %= MOD;
min_sum = 2 * min_sum + arr[i];
min_sum %= MOD;
}
return (max_sum - min_sum + MOD)%MOD;
}
那么如何只获得连续的子集并以更少的时间复杂度解决这个问题。
【问题讨论】:
-
“连续”位实际上是什么意思?如果你只是选择“整个数组”作为数组的一个连续子集,它包含一个最小值和一个最大值,并且它们的总和就是答案?
-
@AndyTurner,这里连续的意思是元素彼此相邻。例如,在数组 [1,2,3] 中,子集 [1,3] 在我的情况下无效,因为它们不相邻。有效的子集是 [1,2],[2,3],[1,2,3]
-
正确。所以,整个数组是整个数组的一个连续(非严格)子集,它的 max 和 min 元素相差最大。
-
我需要我的帖子中提到的所有最大最小差异的总和。根据您的评论,我了解数组 [1,2.3] 最大值为 3,最小值为 1,因此最大值 - 最小值 = 3-1=2。但就我而言,它应该是我帖子中提到的 4。
-
出于好奇,这个问题在现实世界中是否有特定的应用?还是这是一项学术活动?