📌  相关文章
📜  最小化高度之间的最大差异

📅  最后修改于: 2021-10-25 09:21:50             🧑  作者: Mango

给定 n 个塔的高度和一个值 k。我们需要将每个塔的高度增加或减少 k(仅一次),其中 k > 0。任务是最小化修改后最长和最短塔的高度之间的差异并输出该差异。
例子:

Input  : arr[] = {1, 15, 10}, k = 6
Output :  Maximum difference is 5.
Explanation : We change 1 to 7, 15 to 
9 and 10 to 4. Maximum difference is 5
(between 4 and 9). We can't get a lower
difference.

Input : arr[] = {1, 5, 15, 10} 
        k = 3   
Output : Maximum difference is 8
arr[] = {4, 8, 12, 7}

Input : arr[] = {4, 6} 
        k = 10
Output : Maximum difference is 2
arr[] = {14, 16} OR {-6, -4}

Input : arr[] = {6, 10} 
        k = 3
Output : Maximum difference is 2
arr[] = {9, 7} 

Input : arr[] = {1, 10, 14, 14, 14, 15}
        k = 6 
Output: Maximum difference is 5
arr[] = {7, 4, 8, 8, 8, 9} 

Input : arr[] = {1, 2, 3}
        k = 2 
Output: Maximum difference is 2
arr[] = {3, 4, 5} 

来源:Adobe 采访体验 |第 24 组(MTS 校园内)

首先,我们尝试对数组进行排序并使每个塔的高度为最大值。我们通过将所有塔的高度向右减少 k 并向左(k)增加所有塔的高度来做到这一点。您尝试增加高度的塔也可能没有最大高度。因此,我们只需要通过将其与右侧的最后一个元素 an-k 进行比较来检查它是否具有最大高度。由于如果塔的高度大于 an-k,则数组已排序,因此它是可用的最高塔。类似的推理也可以应用于寻找最短的塔。

注意:- 我们不需要考虑 a[i]

C++
#include 
using namespace std;
 
// User function template for C++
 
class Solution {
public:
    // function to find the minimum possible difference
    // between maximum and minimum elements when we have to
    // add/subtract every number by k
    int getMinDiff(int arr[], int n, int k)
    {
        sort(arr, arr + n); // sort the array to get the
                            // corner cases ans.
        int minEle,
            maxEle; // these 2 variables will hold the
                    // between elements max and min value
        int result = arr[n - 1]
                     - arr[0]; // current result when arr[0]
                               // iss min and arr[n-1] is max
 
        for (int i = 1; i <= n - 1; i++) {
            if (arr[i] >= k && arr[n - 1] >= k) {
                maxEle = max(arr[i - 1] + k,
                             arr[n - 1] - k); //
               
                minEle = min(arr[0] + k, arr[i] - k);
 
                result = min(result, maxEle - minEle);
                // if the middle elements max and min
                // difference if less than result then update
                // result.
            }
        }
        return result; // return result.
    }
};
 
//  Driver Code
int main()
{
    int t = 1;
 
    while (t--) {
        int k = 6;
        int n = 3;
        int arr[n] = { 1, 15, 10 };
 
        Solution ob;
        auto ans = ob.getMinDiff(arr, n, k);
        cout << ans << "\n";
    }
    return 0;
}


Java
// Java program to find the minimum possible
// difference between maximum and minimum
// elements when we have to add/subtract
// every number by k
import java.util.*;
 
class GFG {
 
    // Modifies the array by subtracting/adding
    // k to every element such that the difference
    // between maximum and minimum is minimized
    static int getMinDiff(int arr[], int n, int k)
    {
        if (n == 1)
        return 0;
 
        // Sort all elements
        Arrays.sort(arr);
 
        // Initialize result
        int ans = arr[n-1] - arr[0];
 
        // Handle corner elements
        int small = arr[0] + k;
        int big = arr[n-1] - k;
        int temp = 0;
         
        if (small > big)
        {
            temp = small;
            small = big;
            big = temp;
        }
 
        // Traverse middle elements
        for (int i = 1; i < n-1; i ++)
        {
            int subtract = arr[i] - k;
            int add = arr[i] + k;
 
            // If both subtraction and addition
            // do not change diff
            if (subtract >= small || add <= big)
                continue;
 
            // Either subtraction causes a smaller
            // number or addition causes a greater
            // number. Update small or big using
            // greedy approach (If big - subtract
            // causes smaller diff, update small
            // Else update big)
            if (big - subtract <= add - small)
                small = subtract;
            else
                big = add;
        }
 
        return Math.min(ans, big - small);
    }
 
    // Driver function to test the above function
    public static void main(String[] args)
    {
        int arr[] = {4, 6};
        int n = arr.length;
        int k = 10;
        System.out.println("Maximum difference is "+
                            getMinDiff(arr, n, k));
    }
}
// This code is contributed by Prerna Saini


Python3
def getMinDiff(arr, n, k):
        arr.sort()  #sorting the array
        ans=arr[n-1]-arr[0] #it's same as substracting an+k-(ao+k) or an-k-(a0-k)
        small,big=0,0
         
        for i in range(1,n):#trying to make each tower highest
          small=min(arr[0]+k,arr[i]-k) #finding minimum tower height
          big=max(arr[i-1]+k,arr[-1]-k) #finding maximum tower height
          ans=min(ans,big-small) #checking whether we get smaller value as result
             
             
             
        return ans
arr=[1, 10, 14, 14, 14, 15]
k=6
print(getMinDiff(arr,len(arr),k))


C#
// C# program to find the minimum
// possible difference between
// maximum and minimum elements
// when we have to add/subtract
// every number by k
using System;
 
class GFG
{
 
// Modifies the array by subtracting/adding
// k to every element such that the difference
// between maximum and minimum is minimized
static int getMinDiff(int[] arr, int n, int k)
{
    if (n == 1)
    return 0;
 
    // Sort all elements
    Array.Sort(arr);
 
    // Initialize result
    int ans = arr[n - 1] - arr[0];
 
    // Handle corner elements
    int small = arr[0] + k;
    int big = arr[n - 1] - k;
    int temp = 0;
     
    if (small > big)
    {
        temp = small;
        small = big;
        big = temp;
    }
 
    // Traverse middle elements
    for (int i = 1; i < n - 1; i ++)
    {
        int subtract = arr[i] - k;
        int add = arr[i] + k;
 
        // If both subtraction and
        // addition do not change diff
        if (subtract >= small || add <= big)
            continue;
 
        // Either subtraction causes a smaller
        // number or addition causes a greater
        // number. Update small or big using
        // greedy approach (If big - subtract
        // causes smaller diff, update small
        // Else update big)
        if (big - subtract <= add - small)
            small = subtract;
        else
            big = add;
    }
 
    return Math.Min(ans, big - small);
}
 
// Driver Code
public static void Main()
{
    int[] arr = {4, 6};
    int n = arr.Length;
    int k = 10;
    Console.Write("Maximum difference is "+
                    getMinDiff(arr, n, k));
}
}
 
// This code is contributed
// by ChitraNayal


PHP
 $big)
    {
        $temp = $small;
        $small = $big;
        $big = $temp;
    }
     
    // Traverse middle elements
    for ($i = 1; $i < $n - 1; $i ++)
    {
        $subtract = $arr[$i] - $k;
        $add = $arr[$i] + $k;
 
        // If both subtraction and
        // addition do not change diff
        if ($subtract >= $small || $add <= $big)
            continue;
 
        // Either subtraction causes a smaller
        // number or addition causes a greater
        // number. Update small or big using
        // greedy approach (If big - subtract
        // causes smaller diff, update small
        // Else update big)
        if ($big - $subtract <= $add - $small)
            $small = $subtract;
        else
            $big = $add;
    }
 
    return min($ans, $big - $small);
}
 
// Driver Code
$arr = array(4, 6);
$n = sizeof($arr);
$k = 10;
echo "Maximum difference is ";
echo getMinDiff($arr, $n, $k);
 
// This code is contributed by ihritik
?>


Javascript


输出

5

时间复杂度: O(nlogn)

空间复杂度: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程