所有子数组的最大值和最小值的绝对差之和
给定一个包含 N 个整数的数组 arr,任务是找到所有子数组的最大值和最小值的绝对差之和。
例子:
Input: arr[] = {1, 4, 3}
Output: 7
Explanation: The following are the six subarrays:
[1] : maximum – minimum= 1 – 1 = 0
[4] : maximum – minimum= 4 – 4 = 0
[3] : maximum – minimum= 3 – 3 = 0
[1, 4] : maximum – minimum= 4 – 1 = 3
[4, 3] : maximum – minimum= 4 – 3 = 1
[1, 4, 3] : maximum – minimum= 4 – 1 = 3
As a result, the total sum is: 0 + 0 + 0 + 3 + 1 + 3 = 7
Input: arr[] = {1, 6, 3}
Output: 13
方法:方法是找到所有可能的子数组,并保持它们的最大值和最小值,然后用它们来计算总和。现在,请按照以下步骤解决此问题:
- 创建一个变量sum来存储最终答案并将其初始化为 0。
- 在每次迭代中运行从i=0到i
的循环: - 创建两个变量mx和mn分别存储子数组的最大值和最小值。
- 将mx和mn初始化为arr[i] 。
- 现在,从j=i到j
运行另一个循环: - 该循环的每次迭代都用于计算从i到j的子数组的最大值和最小值。
- 因此,将mx更改为mx和arr[j]中的最大值。
- 并将mn更改为mn和arr[j]的最小值。
- 现在,将(mx-mn)添加到sum 。
- 返回 sum 作为这个问题的最终答案。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the sum
// of the absolute difference
// of maximum and minimum of all subarrays
int sumOfDiff(vector& arr)
{
int sum = 0;
int n = arr.size();
for (int i = 0; i < n; i++) {
int mn = arr[i];
int mx = arr[i];
for (int j = i; j < n; j++) {
mx = max(mx, arr[j]);
mn = min(mn, arr[j]);
sum += (mx - mn);
}
}
return sum;
}
// Driver Code
int main()
{
vector arr = { 1, 6, 3 };
cout << sumOfDiff(arr);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
public class GFG
{
// Function to find the sum
// of the absolute difference
// of maximum and minimum of all subarrays
static int sumOfDiff(int []arr)
{
int sum = 0;
int n = arr.length;
for (int i = 0; i < n; i++) {
int mn = arr[i];
int mx = arr[i];
for (int j = i; j < n; j++) {
mx = Math.max(mx, arr[j]);
mn = Math.min(mn, arr[j]);
sum += (mx - mn);
}
}
return sum;
}
// Driver Code
public static void main(String args[])
{
int []arr = { 1, 6, 3 };
System.out.println(sumOfDiff(arr));
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python code for the above approach
# Function to find the sum
# of the absolute difference
# of maximum and minimum of all subarrays
def sumOfDiff(arr):
sum = 0
n = len(arr)
for i in range(n):
mn = arr[i]
mx = arr[i]
for j in range(i, n):
mx = max(mx, arr[j])
mn = min(mn, arr[j])
sum += (mx - mn)
return sum
# Driver Code
arr = [1, 6, 3]
print(sumOfDiff(arr))
# This code is contributed by Saurabh Jaiswal
C#
// C# program for the above approach
using System;
class GFG{
// Function to find the sum of the absolute
// difference of maximum and minimum of all
// subarrays
static int sumOfDiff(int []arr)
{
int sum = 0;
int n = arr.Length;
for(int i = 0; i < n; i++)
{
int mn = arr[i];
int mx = arr[i];
for(int j = i; j < n; j++)
{
mx = Math.Max(mx, arr[j]);
mn = Math.Min(mn, arr[j]);
sum += (mx - mn);
}
}
return sum;
}
// Driver Code
public static void Main()
{
int []arr = { 1, 6, 3 };
Console.Write(sumOfDiff(arr));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
13
时间复杂度: O(N 2 )
辅助空间: O(1)