📌  相关文章
📜  计算数组中对的最小和最大和之间的绝对差

📅  最后修改于: 2021-04-17 19:08:52             🧑  作者: Mango

给定一个由N个整数组成的数组arr [] ,任务是找到任意对元素(arr [i],arr [j])的最小和最大和之间的绝对差,使得(i ( arr [i]

例子:

方法:解决给定问题的想法是创建两个辅助数组,以存储给定数组后缀的每个索引的后缀的最小值和最大值,然后找到所需的绝对差。
请按照以下步骤解决问题:

  • 初始化两个变量maxSumminSum ,以根据给定条件存储给定数组中的一对元素的最大和最小和。
  • 初始化两个数组,例如大小为N的suffixMax []suffixMin [] ,以存储数组arr []的每个索引的后缀的最大值和最小值。
  • 反向遍历给定数组arr []并在每个索引处更新suffixMin []suffixMax []
  • 现在,迭代范围为[0,N – 1]并执行以下步骤:
    • 如果当前元素arr [i]小于suffixMax [i] ,则将maxSum的值更新为maxSum(arr [i] + suffixMax [i])的最大值
    • 如果当前元素arr [i]小于suffixMin [i] ,则将minSum的值更新为minSum(arr [i] + suffixMin [i])的最小值
  • 完成上述步骤后,打印值(maxSum – minSum)作为结果差。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the difference between
// the maximum and minimum sum of a pair
// (arr[i], arr[j]) from the array such
// that i < j and arr[i] < arr[j]
int GetDiff(int A[], int N)
{
    // Stores the maximum from
    // the suffix of the array
    int SuffMaxArr[N];
 
    // Set the last element
    SuffMaxArr[N - 1] = A[N - 1];
 
    // Traverse the remaining array
    for (int i = N - 2; i >= 0; --i) {
 
        // Update the maximum from suffix
        // for the remaining indices
        SuffMaxArr[i] = max(SuffMaxArr[i + 1],
                            A[i + 1]);
    }
 
    // Stores the maximum sum of any pair
    int MaximumSum = INT_MIN;
 
    // Calculate the maximum sum
    for (int i = 0; i < N - 1; i++) {
        if (A[i] < SuffMaxArr[i])
            MaximumSum
                = max(MaximumSum,
                      A[i] + SuffMaxArr[i]);
    }
 
    // Stores the maximum sum of any pair
    int MinimumSum = INT_MAX;
 
    // Stores the minimum of suffixes
    // from the given array
    int SuffMinArr[N];
 
    // Set the last element
    SuffMinArr[N - 1] = INT_MAX;
 
    // Traverse the remaining array
    for (int i = N - 2; i >= 0; --i) {
 
        // Update the maximum from suffix
        // for the remaining indices
        SuffMinArr[i] = min(SuffMinArr[i + 1],
                            A[i + 1]);
    }
 
    // Calculate the minimum sum
    for (int i = 0; i < N - 1; i++) {
 
        if (A[i] < SuffMinArr[i]) {
            MinimumSum = min(MinimumSum,
                             A[i] + SuffMinArr[i]);
        }
    }
 
    // Return the resultant difference
    return abs(MaximumSum - MinimumSum);
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 4, 1, 3, 7, 5, 6 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << GetDiff(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to find the difference between
// the maximum and minimum sum of a pair
// (arr[i], arr[j]) from the array such
// that i < j and arr[i] < arr[j]
static int GetDiff(int A[], int N)
{
     
    // Stores the maximum from
    // the suffix of the array
    int SuffMaxArr[] = new int[N];
 
    // Set the last element
    SuffMaxArr[N - 1] = A[N - 1];
 
    // Traverse the remaining array
    for(int i = N - 2; i >= 0; --i)
    {
         
        // Update the maximum from suffix
        // for the remaining indices
        SuffMaxArr[i] = Math.max(SuffMaxArr[i + 1],
                                          A[i + 1]);
    }
 
    // Stores the maximum sum of any pair
    int MaximumSum = Integer.MIN_VALUE;
 
    // Calculate the maximum sum
    for(int i = 0; i < N - 1; i++)
    {
        if (A[i] < SuffMaxArr[i])
            MaximumSum = Math.max(MaximumSum,
                                  A[i] + SuffMaxArr[i]);
    }
 
    // Stores the maximum sum of any pair
    int MinimumSum = Integer.MAX_VALUE;
 
    // Stores the minimum of suffixes
    // from the given array
    int SuffMinArr[] = new int[N];
 
    // Set the last element
    SuffMinArr[N - 1] = Integer.MAX_VALUE;
 
    // Traverse the remaining array
    for(int i = N - 2; i >= 0; --i)
    {
         
        // Update the maximum from suffix
        // for the remaining indices
        SuffMinArr[i] = Math.min(SuffMinArr[i + 1],
                                          A[i + 1]);
    }
 
    // Calculate the minimum sum
    for(int i = 0; i < N - 1; i++)
    {
        if (A[i] < SuffMinArr[i])
        {
            MinimumSum = Math.min(MinimumSum,
                                  A[i] + SuffMinArr[i]);
        }
    }
 
    // Return the resultant difference
    return Math.abs(MaximumSum - MinimumSum);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 4, 1, 3, 7, 5, 6 };
    int N = arr.length;
 
    // Function Call
    System.out.println(GetDiff(arr, N));
}
}
 
// This code is contributed by Kingash


Python3
# Python 3 program for the above approach
import sys
 
# Function to find the difference between
# the maximum and minimum sum of a pair
# (arr[i], arr[j]) from the array such
# that i < j and arr[i] < arr[j]
def GetDiff(A, N):
   
    # Stores the maximum from
    # the suffix of the array
    SuffMaxArr = [0 for i in range(N)]
 
    # Set the last element
    SuffMaxArr[N - 1] = A[N - 1]
 
    # Traverse the remaining array
    i = N-2
    while(i >= 0):
        # Update the maximum from suffix
        # for the remaining indices
        SuffMaxArr[i] = max(SuffMaxArr[i + 1], A[i + 1])
        i -= 1
 
    # Stores the maximum sum of any pair
    MaximumSum = -sys.maxsize-1
 
    # Calculate the maximum sum
    for i in range(N-1):
        if (A[i] < SuffMaxArr[i]):
            MaximumSum = max(MaximumSum, A[i] + SuffMaxArr[i])
 
    # Stores the maximum sum of any pair
    MinimumSum = sys.maxsize
 
    # Stores the minimum of suffixes
    # from the given array
    SuffMinArr = [0 for i in range(N)]
 
    # Set the last element
    SuffMinArr[N - 1] = sys.maxsize
 
    # Traverse the remaining array
    i = N-2
    while(i >= 0):
       
        # Update the maximum from suffix
        # for the remaining indices
        SuffMinArr[i] = min(SuffMinArr[i + 1], A[i + 1])
        i -= 1
 
    # Calculate the minimum sum
    for i in range(N - 1):
        if (A[i] < SuffMinArr[i]):
            MinimumSum = min(MinimumSum,A[i] + SuffMinArr[i])
 
    # Return the resultant difference
    return abs(MaximumSum - MinimumSum)
 
# Driver Code
if __name__ == '__main__':
    arr = [2, 4, 1, 3, 7, 5, 6]
    N = len(arr)
     
    # Function Call
    print(GetDiff(arr, N))
 
    # This code is contributed by SURENDRA_GANGWAR.


C#
// C# Program to implement
// the above approach
using System;
 
class GFG
{
 
// Function to find the difference between
// the maximum and minimum sum of a pair
// (arr[i], arr[j]) from the array such
// that i < j and arr[i] < arr[j]
static int GetDiff(int[] A, int N)
{
     
    // Stores the maximum from
    // the suffix of the array
    int[] SuffMaxArr = new int[N];
 
    // Set the last element
    SuffMaxArr[N - 1] = A[N - 1];
 
    // Traverse the remaining array
    for(int i = N - 2; i >= 0; --i)
    {
         
        // Update the maximum from suffix
        // for the remaining indices
        SuffMaxArr[i] = Math.Max(SuffMaxArr[i + 1],
                                          A[i + 1]);
    }
 
    // Stores the maximum sum of any pair
    int MaximumSum = Int32.MinValue;
 
    // Calculate the maximum sum
    for(int i = 0; i < N - 1; i++)
    {
        if (A[i] < SuffMaxArr[i])
            MaximumSum = Math.Max(MaximumSum,
                                  A[i] + SuffMaxArr[i]);
    }
 
    // Stores the maximum sum of any pair
    int MinimumSum = Int32.MaxValue;
 
    // Stores the minimum of suffixes
    // from the given array
    int[] SuffMinArr = new int[N];
 
    // Set the last element
    SuffMinArr[N - 1] = Int32.MaxValue;
 
    // Traverse the remaining array
    for(int i = N - 2; i >= 0; --i)
    {
         
        // Update the maximum from suffix
        // for the remaining indices
        SuffMinArr[i] = Math.Min(SuffMinArr[i + 1],
                                          A[i + 1]);
    }
 
    // Calculate the minimum sum
    for(int i = 0; i < N - 1; i++)
    {
        if (A[i] < SuffMinArr[i])
        {
            MinimumSum = Math.Min(MinimumSum,
                                  A[i] + SuffMinArr[i]);
        }
    }
 
    // Return the resultant difference
    return Math.Abs(MaximumSum - MinimumSum);
}
 
// Driver Code
public static void Main(String[] args)
{
    int[] arr = { 2, 4, 1, 3, 7, 5, 6 };
    int N = arr.Length;
 
    // Function Call
    Console.WriteLine(GetDiff(arr, N));
}
}
 
// This code is contributed by code_hunt.


输出:
7

时间复杂度: O(N)
辅助空间: O(N)