Минимизируйте разницу между минимальным и максимальным элементами
Опубликовано: 5 Января, 2022
Учитывая массив целые числа и целое число . Допускается изменять элемент, увеличивая или уменьшая его на k (только один раз).
Задача минимизировать и напечатать максимальную разницу между самой короткой и самой длинной башнями.
Примеры:
Ввод : arr [] = {1, 10, 8, 5}, k = 2 Выход : максимальная разница в высоте = 5. Объяснение: измененный arr [] = {3, 8, 6, 7} максимальная разница: 5 Ввод : arr [] = {3, 16, 12, 9, 20}, k = 3 Мощность : макс. Перепад высот: 11
Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.
Подход:
- Найдите максимальные и минимальные элементы, присутствующие в массиве.
- Проверьте, меньше ли разница между элементом max и min k или нет:
- Если да, то верните разницу между максимальным и минимальным элементом.
- в противном случае перейдите к шагу 3.
- Вычислите среднее значение максимального и минимального элементов массива.
- Пройдите по массиву и выполните следующие операции:
- Если элемент массива больше среднего, уменьшите его на k.
- Если элемент массива меньше среднего, увеличьте его на k.
- Вернуть разницу между максимальным и минимальным элементами измененного массива.
Ниже представлена реализация вышеуказанного подхода:
C ++
// C++ program to minimize the difference between // minimum and maximum elements #include <bits/stdc++.h> using namespace std; // Function to minimize the difference between // minimum and maximum elements int minimizeDiff( int * arr, int n, int k) { // Find max and min elements of the array int max = *(max_element(arr, arr + n)); int min = *(min_element(arr, arr + n)); // Check whether the difference between // the max and min element is less than // or equal to k or not if ((max - min) <= k) { return (max - min); } // Calculate average of max and min int avg = (max + min) / 2; for ( int i = 0; i < n; i++) { // If the array element is greater than the // average then decrease it by k if (arr[i] > avg) arr[i] -= k; // If the array element is smaller than the // average then increase it by k else arr[i] += k; } // Find max and min of the modified array max = *(max_element(arr, arr + n)); min = *(min_element(arr, arr + n)); // return the new difference return (max - min); } // Driver code int main() { int arr[] = { 3, 16, 12, 9, 20 }; int n = 5; int k = 3; cout << "Max height difference = " << minimizeDiff(arr, n, k) << endl; return 0; } |
Джава
// Java program to minimize the difference between // minimum and maximum elements import java.util.*; class GFG { // Function to minimize the difference between // minimum and maximum elements static int minimizeDiff( int [] arr, int n, int k) { // Find max and min elements of the array int max = Arrays.stream(arr).max().getAsInt(); int min = Arrays.stream(arr).min().getAsInt(); // Check whether the difference between // the max and min element is less than // or equal to k or not if ((max - min) <= k) { return (max - min); } // Calculate average of max and min int avg = (max + min) / 2 ; for ( int i = 0 ; i < n; i++) { // If the array element is greater than the // average then decrease it by k if (arr[i] > avg) { arr[i] -= k; } // If the array element is smaller than the // average then increase it by k else { arr[i] += k; } } // Find max and min of the modified array max = Arrays.stream(arr).max().getAsInt(); min = Arrays.stream(arr).min().getAsInt(); // return the new difference return (max - min); } // Driver code public static void main(String[] args) { int arr[] = { 3 , 16 , 12 , 9 , 20 }; int n = 5 ; int k = 3 ; System.out.println( "Max height difference = " + minimizeDiff(arr, n, k)); } } // This code has been contributed by 29AjayKumar |
Python3
# Python 3 program to minimize the # difference between minimum and # maximum elements # Function to minimize the difference # between minimum and maximum elements def minimizeDiff(arr, n, k) : # Find max and min elements # of the array max_element = max (arr) min_element = min (arr) # Check whether the difference between # the max and min element is less than # or equal to k or not if ((max_element - min_element) < = k) : return (max_element - min_element) # Calculate average of max and min avg = (max_element + min_element) / / 2 for i in range (n): # If the array element is greater than # the average then decrease it by k if (arr[i] > avg) : arr[i] - = k # If the array element is smaller than # the average then increase it by k else : arr[i] + = k # Find max and min of the # modified array max_element = max (arr) min_element = min (arr) # return the new difference return (max_element - min_element); # Driver code if __name__ = = "__main__" : arr = [ 3 , 16 , 12 , 9 , 20 ] n = 5 k = 3 print ( "Max height difference =" , minimizeDiff(arr, n, k)) # This code is contributed by Ryuga |
C #
// C# program to minimize the difference between // minimum and maximum elements using System; using System.Linq; class GFG { // Function to minimize the difference between // minimum and maximum elements static int minimizeDiff( int [] arr, int n, int k) { // Find max and min elements of the array int max = arr.Max(); int min = arr.Min(); // Check whether the difference between // the max and min element is less than // or equal to k or not if ((max - min) <= k) { return (max - min); } // Calculate average of max and min int avg = (max + min) / 2; for ( int i = 0; i < n; i++) { // If the array element is greater than the // average then decrease it by k if (arr[i] > avg) { arr[i] -= k; } // If the array element is smaller than the // average then increase it by k else { arr[i] += k; } } // Find max and min of the modified array max = arr.Max(); min = arr.Min(); // return the new difference return (max - min); } // Driver code public static void Main() { int []arr = {3, 16, 12, 9, 20}; int n = 5; int k = 3; Console.WriteLine( "Max height difference = " + minimizeDiff(arr, n, k)); } } /* This code contributed by PrinciRaj1992 */ |
PHP
<?php // PHP program to minimize the difference // between minimum and maximum elements // Function to minimize the difference // between minimum and maximum elements function minimizeDiff(& $arr , $n , $k ) { // Find max and min elements // of the array $max = max( $arr ); $min = min( $arr ); // Check whether the difference between // the max and min element is less than // or equal to k or not if (( $max - $min ) <= $k ) { return ( $max - $min ); } // Calculate average of max and min $avg = ( $max + $min ) / 2; for ( $i = 0; $i < $n ; $i ++) { // If the array element is greater than // the average then decrease it by k if ( $arr [ $i ] > $avg ) $arr [ $i ] -= $k ; // If the array element is smaller than // the average then increase it by k else $arr [ $i ] += $k ; } // Find max and min of the // modified array $max = max( $arr ); $min = min( $arr ); // return the new difference return ( $max - $min ); } // Driver code $arr = array ( 3, 16, 12, 9, 20 ); $n = 5; $k = 3; echo "Max height difference = " . minimizeDiff( $arr , $n , $k ). "
" ; // This code is contributed by ita_c ?> |
Javascript
<script> // Javascript program to minimize // the difference between // minimum and maximum elements // Function to minimize the difference between // minimum and maximum elements function minimizeDiff(arr,n,k) { // Find max and min elements of the array let max = Math.max(...arr); let min = Math.min(...arr); // Check whether the difference between // the max and min element is less than // or equal to k or not if ((max - min) <= k) { return (max - min); } // Calculate average of max and min let avg = Math.floor((max + min) / 2); for (let i = 0; i < n; i++) { // If the array element is greater than the // average then decrease it by k if (arr[i] > avg) { arr[i] -= k; } // If the array element is smaller than the // average then increase it by k else { arr[i] += k; } } // Find max and min of the modified array max = Math.max(...arr); min = Math.min(...arr); // return the new difference return (max - min); } // Driver code let arr=[3, 16, 12, 9, 20]; let n = 5; let k = 3; document.write( "Max height difference = " + minimizeDiff(arr, n, k)); // This code is contributed by avanitrachhadiya2155 </script> |
Выход:
Max height difference = 11