📜  排序形式的数组中的最大相邻差

📅  最后修改于: 2021-04-23 07:27:54             🧑  作者: Mango

给定一个数组,以排序形式找出其两个连续元素之间的最大差值。
例子:

Input: arr[] = {1, 10, 5}
Output: 5
Sorted array would be {1, 5, 10} and
maximum adjacent difference would be 
10 - 5 = 5

Input: arr[] = {2, 4, 8, 11}
Output: 4

天真的解决方案:

首先对数组进行排序,然后遍历数组并跟踪相邻元素之间的最大差异。
该方法的时间复杂度为O(nlogn)。

高效的解决方案:
解决方案基于鸽孔分选的思想。无需对数组进行排序,只需填充存储桶并跟踪每个存储桶的最大值和最小值。如果发现一个空存储桶,则最大间隙将是前一个存储桶中最大值下一个存储桶中的最小值之差。
下面是上述方法的代码:

C++
// CPP program to find maximum adjacent difference
// between two adjacent after sorting.
#include 
using namespace std;
 
int maxSortedAdjacentDiff(int* arr, int n)
{
    // Find maximum and minimum in arr[]
    int maxVal = arr[0], minVal = arr[0];
    for (int i = 1; i < n; i++) {
        maxVal = max(maxVal, arr[i]);
        minVal = min(minVal, arr[i]);
    }
 
    // Arrays to store maximum and minimum values
    // in n-1 buckets of differences.
    int maxBucket[n - 1];
    int minBucket[n - 1];
    fill_n(maxBucket, n - 1, INT_MIN);
    fill_n(minBucket, n - 1, INT_MAX);
 
    // Expected gap for every bucket.
    float delta = (float)(maxVal - minVal) / (float)(n - 1);
 
    // Traversing through array elements and
    // filling in appropriate bucket if bucket
    // is empty. Else updating bucket values.
    for (int i = 0; i < n; i++) {
        if (arr[i] == maxVal || arr[i] == minVal)
            continue;
 
        // Finding index of bucket.
        int index = (float)(floor(arr[i] - minVal) / delta);
 
        // Filling/Updating maximum value of bucket
        if (maxBucket[index] == INT_MIN)
            maxBucket[index] = arr[i];
        else
            maxBucket[index]
                = max(maxBucket[index], arr[i]);
 
        // Filling/Updating minimum value of bucket
        if (minBucket[index] == INT_MAX)
            minBucket[index] = arr[i];
        else
            minBucket[index]
                = min(minBucket[index], arr[i]);
    }
 
    // Finding maximum difference between maximum value
    // of previous bucket minus minimum of current bucket.
    int prev_val = minVal;
    int max_gap = 0;
    for (int i = 0; i < n - 1; i++) {
        if (minBucket[i] == INT_MAX)
            continue;
        max_gap = max(max_gap, minBucket[i] - prev_val);
        prev_val = maxBucket[i];
    }
    max_gap = max(max_gap, maxVal - prev_val);
 
    return max_gap;
}
 
int main()
{
    int arr[] = { 1, 10, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << maxSortedAdjacentDiff(arr, n) << endl;
    return 0;
}


Java
// Java program for the above approach
import java.util.Arrays;
 
// Java program to find maximum adjacent difference
// between two adjacent after sorting.
class GFG {
 
    static int maxSortedAdjacentDiff(int[] arr, int n)
    {
        // Find maximum and minimum in arr[]
        int maxVal = arr[0];
        int minVal = arr[0];
        for (int i = 1; i < n; i++) {
            maxVal = Math.max(maxVal, arr[i]);
            minVal = Math.min(minVal, arr[i]);
        }
 
        // Arrays to store maximum and minimum values
        // in n-1 buckets of differences.
        int maxBucket[] = new int[n - 1];
        int minBucket[] = new int[n - 1];
        Arrays.fill(maxBucket, 0, n - 1, Integer.MIN_VALUE);
        Arrays.fill(minBucket, 0, n - 1, Integer.MAX_VALUE);
 
        // Expected gap for every bucket.
        float delta
            = (float)(maxVal - minVal) / (float)(n - 1);
 
        // Traversing through array elements and
        // filling in appropriate bucket if bucket
        // is empty. Else updating bucket values.
        for (int i = 0; i < n; i++) {
            if (arr[i] == maxVal || arr[i] == minVal) {
                continue;
            }
 
            // Finding index of bucket.
            int index = (int)(Math.round((arr[i] - minVal)
                                         / delta));
 
            // Filling/Updating maximum value of bucket
            if (maxBucket[index] == Integer.MIN_VALUE) {
                maxBucket[index] = arr[i];
            }
            else {
                maxBucket[index]
                    = Math.max(maxBucket[index], arr[i]);
            }
 
            // Filling/Updating minimum value of bucket
            if (minBucket[index] == Integer.MAX_VALUE) {
                minBucket[index] = arr[i];
            }
            else {
                minBucket[index]
                    = Math.min(minBucket[index], arr[i]);
            }
        }
 
        // Finding maximum difference between maximum value
        // of previous bucket minus minimum of current
        // bucket.
        int prev_val = minVal;
        int max_gap = 0;
        for (int i = 0; i < n - 1; i++) {
            if (minBucket[i] == Integer.MAX_VALUE) {
                continue;
            }
            max_gap = Math.max(max_gap,
                               minBucket[i] - prev_val);
            prev_val = maxBucket[i];
        }
        max_gap = Math.max(max_gap, maxVal - prev_val);
 
        return max_gap;
    }
 
    // Driver program to run the case
    public static void main(String[] args)
    {
 
        int arr[] = { 1, 10, 5 };
        int n = arr.length;
        System.out.println(maxSortedAdjacentDiff(arr, n));
    }
}


Python3
# Python3 program to find maximum adjacent
# difference between two adjacent after sorting.
 
def maxSortedAdjacentDiff(arr, n):
 
    # Find maximum and minimum in arr[]
    maxVal, minVal = arr[0], arr[0]
    for i in range(1, n):
        maxVal = max(maxVal, arr[i])
        minVal = min(minVal, arr[i])
 
    # Arrays to store maximum and minimum
    # values in n-1 buckets of differences.
    maxBucket = [INT_MIN] * (n - 1)
    minBucket = [INT_MAX] * (n - 1)
     
    # Expected gap for every bucket.
    delta = (maxVal - minVal) // (n - 1)
 
    # Traversing through array elements and
    # filling in appropriate bucket if bucket
    # is empty. Else updating bucket values.
    for i in range(0, n):
        if arr[i] == maxVal or arr[i] == minVal:
            continue
 
        # Finding index of bucket.
        index = (arr[i] - minVal) // delta
 
        # Filling/Updating maximum value
        # of bucket
        if maxBucket[index] == INT_MIN:
            maxBucket[index] = arr[i]
        else:
            maxBucket[index] = max(maxBucket[index],
                                             arr[i])
 
        # Filling/Updating minimum value of bucket
        if minBucket[index] == INT_MAX:
            minBucket[index] = arr[i]
        else:
            minBucket[index] = min(minBucket[index],
                                             arr[i])
     
    # Finding maximum difference between 
    # maximum value of previous bucket
    # minus minimum of current bucket.
    prev_val, max_gap = minVal, 0
     
    for i in range(0, n - 1):
        if minBucket[i] == INT_MAX:
            continue
             
        max_gap = max(max_gap,
                      minBucket[i] - prev_val)
        prev_val = maxBucket[i]
     
    max_gap = max(max_gap, maxVal - prev_val)
 
    return max_gap
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 10, 5]
    n = len(arr)
    INT_MIN, INT_MAX = float('-inf'), float('inf')
     
    print(maxSortedAdjacentDiff(arr, n))
 
# This code is contributed by Rituraj Jain


C#
// C# program to find maximum
// adjacent difference between
// two adjacent after sorting.
using System;
using System.Linq;
 
class GFG
{
static int maxSortedAdjacentDiff(int[] arr,    
                                 int n)
{
    // Find maximum and minimum in arr[]
    int maxVal = arr[0];
    int minVal = arr[0];
    for (int i = 1; i < n; i++)
    {
        maxVal = Math.Max(maxVal, arr[i]);
        minVal = Math.Min(minVal, arr[i]);
    }
 
    // Arrays to store maximum and
    // minimum values in n-1 buckets
    // of differences.
    int []maxBucket = new int[n - 1];
    int []minBucket = new int[n - 1];
    maxBucket = maxBucket.Select(i => int.MinValue).ToArray();
    minBucket = minBucket.Select(i => int.MaxValue).ToArray();
     
    // maxBucket.Fill(int.MinValue);
    // Arrays.fill(minBucket, 0, n - 1, Integer.MAX_VALUE);
 
    // Expected gap for every bucket.
    float delta = (float) (maxVal - minVal) /
                  (float) (n - 1);
 
    // Traversing through array elements and
    // filling in appropriate bucket if bucket
    // is empty. Else updating bucket values.
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == maxVal || arr[i] == minVal)
        {
            continue;
        }
 
        // Finding index of bucket.
        int index = (int) (Math.Round((arr[i] -
                             minVal) / delta));
 
        // Filling/Updating maximum value of bucket
        if (maxBucket[index] == int.MinValue)
        {
            maxBucket[index] = arr[i];
        }
        else
        {
            maxBucket[index] = Math.Max(maxBucket[index],
                                                  arr[i]);
        }
 
        // Filling/Updating minimum value of bucket
        if (minBucket[index] == int.MaxValue)
        {
            minBucket[index] = arr[i];
        }
        else
        {
            minBucket[index] = Math.Min(minBucket[index],
                                                  arr[i]);
        }
    }
 
    // Finding maximum difference between
    // maximum value of previous bucket
    // minus minimum of current bucket.
    int prev_val = minVal;
    int max_gap = 0;
    for (int i = 0; i < n - 1; i++)
    {
        if (minBucket[i] == int.MaxValue)
        {
            continue;
        }
        max_gap = Math.Max(max_gap, minBucket[i] -
                                    prev_val);
        prev_val = maxBucket[i];
    }
    max_gap = Math.Max(max_gap, maxVal -
                                prev_val);
 
    return max_gap;
}
 
// Driver Code
public static void Main()
{
    int []arr = {1, 10, 5};
    int n = arr.Length;
    Console.Write(maxSortedAdjacentDiff(arr, n));
}
}
 
// This code contributed by 29AjayKumar


输出:
5

时间复杂度: O(n)
辅助空间: O(n)