给定一个由整数组成的数组arr[] ,任务是将给定的数组拆分为两个子数组,使得它们的最大元素之间的差异最小。
例子:
Input: arr[] = {7, 9, 5, 10}
Output: 1
Explanation:
The subarrays are {5, 10} and {7, 9} with the difference between their maximums = 10 – 9 = 1.
Input: arr[] = {6, 6, 6}
Output: 0
方法:
我们可以观察到,我们需要将数组拆分为两个子数组,使得:
- 如果最大元素在数组中出现多次,则它需要在两个子数组中至少出现一次。
- 否则,最大的和第二大的元素应该出现在不同的子数组中。
这确保了两个子阵列的最大元素之间的差异最大化。
因此,我们需要对数组进行排序,然后最大的 2 个元素之间的差,即 arr[n – 1] 和 arr[n – 2],就是所需的答案。
下面是上述方法的实现:
C++
// C++ Program to split a given
// array such that the difference
// between their maximums is minimized.
#include
using namespace std;
int findMinDif(int arr[], int N)
{
// Sort the array
sort(arr, arr + N);
// Return the difference
// between two highest
// elements
return (arr[N - 1] - arr[N - 2]);
}
// Driver Program
int main()
{
int arr[] = { 7, 9, 5, 10 };
int N = sizeof(arr) / sizeof(arr[0]);
cout << findMinDif(arr, N);
return 0;
}
Java
// Java Program to split a given array
// such that the difference between
// their maximums is minimized.
import java.util.*;
class GFG{
static int findMinDif(int arr[], int N)
{
// Sort the array
Arrays.sort(arr);
// Return the difference between
// two highest elements
return (arr[N - 1] - arr[N - 2]);
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 7, 9, 5, 10 };
int N = arr.length;
System.out.println(findMinDif(arr, N));
}
}
// This code is contributed by offbeat
Python3
# Python3 Program to split a given
# array such that the difference
# between their maximums is minimized.
def findMinDif(arr, N):
# Sort the array
arr.sort()
# Return the difference
# between two highest
# elements
return (arr[N - 1] - arr[N - 2])
# Driver Program
arr = [ 7, 9, 5, 10 ]
N = len(arr)
print(findMinDif(arr, N))
# This code is contributed by yatinagg
C#
// C# Program to split a given array
// such that the difference between
// their maximums is minimized.
using System;
class GFG{
static int findMinDif(int []arr, int N)
{
// Sort the array
Array.Sort(arr);
// Return the difference between
// two highest elements
return (arr[N - 1] - arr[N - 2]);
}
// Driver code
public static void Main()
{
int []arr = { 7, 9, 5, 10 };
int N = arr.Length;
Console.Write(findMinDif(arr, N));
}
}
// This code is contributed by Code_Mech
Javascript
输出:
1
时间复杂度: O(N*log(N)),N是数组的元素个数。
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live