📌  相关文章
📜  最大化每个元素与剩余数组的绝对差之和之间的差

📅  最后修改于: 2021-09-05 11:57:07             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,任务是最大化一个元素与数组中其余元素的绝对差之和之间的差。

例子:

朴素的方法:最简单的想法是遍历数组,对于每个数组元素,使用嵌套循环遍历数组并计算并存储其与剩余数组的绝对差之和。在计算时,跟踪获得的最大和最小总和。最后,打印最大和最小总和之间的差值。
时间复杂度: O(N 2 )
辅助空间: O(1)

高效的方法:为了优化上述方法,该想法基于以下观察:在已排序的数组中,对于任何索引i ,其左侧的元素将更小,而其右侧的元素将更大。可以使用以下公式计算此排序数组中任何元素arr[i]的绝对差之和:

请按照以下步骤解决问题:

  • 初始化totalSum作为0来存储所有的总和的阵列和leftSum的元素作为0存储在任何索引的左元素的总和。
  • 初始化两个变量, MaxINT_MINMinINT_MAX
  • 按升序对数组arr[]进行排序。
  • 使用变量i遍历数组arr[]并执行以下操作:
    • 使用Sum = (i * arr[i]) – leftSum + totalSum – ((N – i – 1) * arr[i]) 中的公式存储arr[i]与其余元素的绝对差之.
    • Max更新为MaxSum最大值
    • Min更新为MinSum最小值
  • 完成上述步骤后,打印MaxMin的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to maximize difference of
// the sum of absolute difference of
// an element with the rest of the
// elements in the array
void findMaxDifference(int arr[], int n)
{
    // Sort the array in ascending order
    sort(arr, arr + n);
 
    // Stores prefix sum at any instant
    int Leftsum = 0;
 
    // Store the total array sum
    int Totalsum = 0;
 
    // Initialize minimum and maximum
    // absolute difference
    int Min = INT_MAX, Max = INT_MIN;
 
    // Traverse the array to find
    // the total array sum
    for (int i = 0; i < n; i++)
        Totalsum += arr[i];
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++) {
 
        // Store the number of
        // elements to its left
        int leftNumbers = i;
 
        // Store the number of
        // elements to its right
        int rightNumbers = n - i - 1;
 
        // Update the sum of elements
        // on its left
        Totalsum = Totalsum - arr[i];
 
        // Store the absolute difference sum
        int sum = (leftNumbers * arr[i])
                  - Leftsum
                  + Totalsum
                  - (rightNumbers * arr[i]);
 
        // Update the Minimum
        Min = min(Min, sum);
 
        // Update the Maximum
        Max = max(Max, sum);
 
        // Update sum of elements
        // on its left
        Leftsum += arr[i];
    }
 
    // Print the result
    cout << Max - Min;
}
 
// Driven Code
int main()
{
    int arr[] = { 1, 2, 4, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
    findMaxDifference(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to maximize difference of
// the sum of absolute difference of
// an element with the rest of the
// elements in the array
static void findMaxDifference(int arr[], int n)
{
   
    // Sort the array in ascending order
    Arrays.sort(arr);
 
    // Stores prefix sum at any instant
    int Leftsum = 0;
 
    // Store the total array sum
    int Totalsum = 0;
 
    // Initialize minimum and maximum
    // absolute difference
    int Min = Integer.MAX_VALUE, Max = Integer.MIN_VALUE;
 
    // Traverse the array to find
    // the total array sum
    for (int i = 0; i < n; i++)
        Totalsum += arr[i];
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++)
    {
 
        // Store the number of
        // elements to its left
        int leftNumbers = i;
 
        // Store the number of
        // elements to its right
        int rightNumbers = n - i - 1;
 
        // Update the sum of elements
        // on its left
        Totalsum = Totalsum - arr[i];
 
        // Store the absolute difference sum
        int sum = (leftNumbers * arr[i])
                  - Leftsum
                  + Totalsum
                  - (rightNumbers * arr[i]);
 
        // Update the Minimum
        Min = Math.min(Min, sum);
 
        // Update the Maximum
        Max = Math.max(Max, sum);
 
        // Update sum of elements
        // on its left
        Leftsum += arr[i];
    }
 
    // Print the result
    System.out.print(Max - Min);
}
 
// Driven Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 4, 7 };
    int N = arr.length;
    findMaxDifference(arr, N);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to maximize difference of
# the sum of absolute difference of
# an element with the rest of the
# elements in the array
def findMaxDifference(arr, n):
   
    # Sort the array in ascending order
    arr = sorted(arr)
 
    # Stores prefix sum at any instant
    Leftsum = 0
 
    # Store the total array sum
    Totalsum = 0
 
    # Initialize minimum and maximum
    # absolute difference
    Min, Max = 10**8, -10**8
 
    # Traverse the array to find
    # the total array sum
    for i in range(n):
        Totalsum += arr[i]
 
    # Traverse the array arr[]
    for i in range(n):
 
        # Store the number of
        # elements to its left
        leftNumbers = i
 
        # Store the number of
        # elements to its right
        rightNumbers = n - i - 1
 
        # Update the sum of elements
        # on its left
        Totalsum = Totalsum - arr[i]
 
        # Store the absolute difference sum
        sum = (leftNumbers * arr[i])- Leftsum + Totalsum - (rightNumbers * arr[i])
 
        # Update the Minimum
        Min = min(Min, sum)
 
        # Update the Maximum
        Max = max(Max, sum)
 
        # Update sum of elements
        # on its left
        Leftsum += arr[i]
 
    # Prthe result
    print (Max - Min)
 
# Driven Code
if __name__ == '__main__':
    arr = [1, 2, 4, 7]
    N = len(arr)
    findMaxDifference(arr, N)
 
# This code is contributed by mohit kumar 29.


C#
// C# Program to implement
// the above approach
using System;
class GFG
{
 
  // Function to maximize difference of
  // the sum of absolute difference of
  // an element with the rest of the
  // elements in the array
  static void findMaxDifference(int[] arr, int n)
  {
 
    // Sort the array in ascending order
    Array.Sort(arr);
 
    // Stores prefix sum at any instant
    int Leftsum = 0;
 
    // Store the total array sum
    int Totalsum = 0;
 
    // Initialize minimum and maximum
    // absolute difference
    int Minn = Int32.MaxValue, Maxx = Int32.MinValue;
 
    // Traverse the array to find
    // the total array sum
    for (int i = 0; i < n; i++)
      Totalsum += arr[i];
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++)
    {
 
      // Store the number of
      // elements to its left
      int leftNumbers = i;
 
      // Store the number of
      // elements to its right
      int rightNumbers = n - i - 1;
 
      // Update the sum of elements
      // on its left
      Totalsum = Totalsum - arr[i];
 
      // Store the absolute difference sum
      int sum = (leftNumbers * arr[i])
        - Leftsum
        + Totalsum
        - (rightNumbers * arr[i]);
 
      // Update the Minimum
      Minn = Math.Min(Minn, sum);
 
      // Update the Maximum
      Maxx = Math.Max(Maxx, sum);
 
      // Update sum of elements
      // on its left
      Leftsum += arr[i];
    }
 
    // Print the result
    Console.WriteLine(Maxx - Minn);
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int[] arr = { 1, 2, 4, 7 };
    int N = arr.Length;
    findMaxDifference(arr, N);
  }
}
 
// This code is contributed by sanjoy_62.


Javascript


输出:
6

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live