给定N个整数的数组arr [] ,任务是从数组中查找元素x ,使得| arr [0] – x | + | arr [1] – x | + | arr [2] – x | +…+ | arr [n – 1] – x |最小化,然后打印最小化的总和。
例子:
Input: arr[] = {1, 3, 9, 3, 6}
Output: 11
The optimal solution is to choose x = 3, which produces the sum
|1 – 3| + |3 – 3| + |9 – 3| + |3 – 3| + |6 – 3| = 2 + 0 + 6 + 0 + 3 = 11
Input: arr[] = {1, 2, 3, 4}
Output: 4
一个简单的解决方案是遍历每个元素,并检查是否给出了最佳解决方案。该解决方案的时间复杂度为O(n * n)
一种有效的方法:总是选择x作为数组的中位数。如果n是偶数,并且有两个中位数,则两个中位数都是最佳选择。该方法的时间复杂度为O(n * log(n)),因为必须对数组进行排序才能找到中值。当找到x(数组的中位数)时,计算并打印最小化的总和。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the minimized sum
int minSum(int arr[], int n)
{
// Sort the array
sort(arr, arr + n);
// Median of the array
int x = arr[n / 2];
int sum = 0;
// Calculate the minimized sum
for (int i = 0; i < n; i++)
sum += abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
int main()
{
int arr[] = { 1, 3, 9, 3, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << minSum(arr, n);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to return the minimized sum
static int minSum(int arr[], int n)
{
// Sort the array
Arrays.sort(arr);
// Median of the array
int x = arr[(int)n / 2];
int sum = 0;
// Calculate the minimized sum
for (int i = 0; i < n; i++)
sum += Math.abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 3, 9, 3, 6 };
int n = arr.length;
System.out.println(minSum(arr, n));
}
}
// This code is contribute by
// Surendra_Gangwar
Python3
# Python3 implementation of the approach
# Function to return the minimized sum
def minSum(arr, n) :
# Sort the array
arr.sort();
# Median of the array
x = arr[n // 2];
sum = 0;
# Calculate the minimized sum
for i in range(n) :
sum += abs(arr[i] - x);
# Return the required sum
return sum;
# Driver code
if __name__ == "__main__" :
arr = [ 1, 3, 9, 3, 6 ];
n = len(arr)
print(minSum(arr, n));
# This code is contributed by Ryuga
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the minimized sum
static int minSum(int []arr, int n)
{
// Sort the array
Array.Sort(arr);
// Median of the array
int x = arr[(int)(n / 2)];
int sum = 0;
// Calculate the minimized sum
for (int i = 0; i < n; i++)
sum += Math.Abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
static void Main()
{
int []arr = { 1, 3, 9, 3, 6 };
int n = arr.Length;
Console.WriteLine(minSum(arr, n));
}
}
// This code is contributed by mits
Javascript
输出:
11
上述解决方案的时间复杂度为O(n Log n)。我们可以使用线性时间算法进一步优化它以在O(n)中工作,以找到第k个最大元素。
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。