📌  相关文章
📜  绝对差为 K 的两个元素之间的最大距离

📅  最后修改于: 2021-10-27 07:25:35             🧑  作者: Mango

给定一个数组arr[]和一个数字K ,任务是找到绝对差为K 的两个元素之间的最大距离。如果无法找到任何最大距离,则打印“-1”

例子:

朴素的方法:这个想法是一个一个地选择每个元素(比如arr[i] ),搜索前一个元素(arr[i] – K)和下一个元素(arr[i] + K) 。如果存在两个元素中的任何一个,则找到当前元素与其下一个或前一个元素之间的最大距离。

时间复杂度: O(N 2 )
辅助空间: O(1)

Efficient Approach:优化上面的方法,思路是使用 哈希图。以下是步骤:

  1. 遍历数组并将第一次出现的索引存储在 HashMap 中。
  2. 现在,对于数组arr[]中的每个元素,检查arr[i] + Karr[i] – K是否存在于哈希图中。
  3. 如果存在,则使用arr[i]更新与两个元素的距离并检查下一个元素。
  4. 打印上述步骤后得到的最大距离。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function that find maximum distance
// between two elements whose absolute
// difference is K
int maxDistance(int arr[], int K, int N)
{
 
    // To store the first index
    map Map;
     
    // Traverse elements and find
    // maximum distance between 2
    // elements whose absolute
    // difference is K
    int maxDist = 0;
 
    for(int i = 0; i < N; i++)
    {
 
        // If this is first occurrence
        // of element then insert
        // its index in map
        if (Map.find(arr[i]) == Map.end())
            Map[arr[i]] = i;
 
        // If next element present in
        // map then update max distance
        if (Map.find(arr[i] + K) != Map.end())
        {
            maxDist = max(maxDist,
                          i - Map[arr[i] + K]);
        }
 
        // If previous element present
        // in map then update max distance
        if (Map.find(arr[i] - K) != Map.end())
        {
            maxDist = max(maxDist,
                          i - Map[arr[i] - K]);
        }
    }
 
    // Return the answer
    if (maxDist == 0)
        return -1;
    else
        return maxDist;
}
 
// Driver code
int main()
{
     
    // Given array arr[]
    int arr[] = { 11, 2, 3, 8, 5, 2 };
     
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Given difference K
    int K = 2;
 
    // Function call
    cout << maxDistance(arr, K, N);
 
    return 0;
}
 
// This code is contributed by divyeshrabadiya07


Java
// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function that find maximum distance
    // between two elements whose absolute
    // difference is K
    static int maxDistance(int[] arr, int K)
    {
 
        // To store the first index
        Map map
            = new HashMap<>();
 
        // Traverse elements and find
        // maximum distance between 2
        // elements whose absolute
        // difference is K
        int maxDist = 0;
 
        for (int i = 0; i < arr.length; i++) {
 
            // If this is first occurrence
            // of element then insert
            // its index in map
            if (!map.containsKey(arr[i]))
                map.put(arr[i], i);
 
            // If next element present in
            // map then update max distance
            if (map.containsKey(arr[i] + K)) {
                maxDist
                    = Math.max(
                        maxDist,
                        i - map.get(arr[i] + K));
            }
 
            // If previous element present
            // in map then update max distance
            if (map.containsKey(arr[i] - K)) {
                maxDist
                    = Math.max(maxDist,
                            i - map.get(arr[i] - K));
            }
        }
 
        // Return the answer
        if (maxDist == 0)
            return -1;
        else
            return maxDist;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Given array arr[]
        int[] arr = { 11, 2, 3, 8, 5, 2 };
 
        // Given difference K
        int K = 2;
 
        // Function call
        System.out.println(
            maxDistance(arr, K));
    }
}


Python3
# Python3 program for the above approach
 
# Function that find maximum distance
# between two elements whose absolute
# difference is K
def maxDistance(arr, K):
     
    # To store the first index
    map = {}
     
    # Traverse elements and find
    # maximum distance between 2
    # elements whose absolute
    # difference is K
    maxDist = 0
     
    for i in range(len(arr)):
         
        # If this is first occurrence
        # of element then insert
        # its index in map
        if not arr[i] in map:
            map[arr[i]] = i
             
        # If next element present in
        # map then update max distance
        if arr[i] + K in map:
            maxDist = max(maxDist,
                        i - map[arr[i] + K])
             
        # If previous element present
        # in map then update max distance
        if arr[i] - K in map:
            maxDist = max(maxDist,
                        i - map[arr[i] - K])
             
    # Return the answer
    if maxDist == 0:
        return -1
    else:
        return maxDist
     
# Driver code
 
# Given array arr[]
arr = [ 11, 2, 3, 8, 5, 2 ]
 
# Given difference K
K = 2
 
# Function call
print(maxDistance(arr,K))
 
# This code is contributed by Stuti Pathak


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function that find maximum distance
// between two elements whose absolute
// difference is K
static int maxDistance(int[] arr, int K)
{
 
    // To store the first index
    Dictionary map = new Dictionary();
 
    // Traverse elements and find
    // maximum distance between 2
    // elements whose absolute
    // difference is K
    int maxDist = 0;
 
    for (int i = 0; i < arr.Length; i++)
    {
 
    // If this is first occurrence
    // of element then insert
    // its index in map
    if (!map.ContainsKey(arr[i]))
        map.Add(arr[i], i);
 
    // If next element present in
    // map then update max distance
    if (map.ContainsKey(arr[i] + K))
    {
        maxDist = Math.Max(maxDist,
                        i - map[arr[i] + K]);
    }
 
    // If previous element present
    // in map then update max distance
    if (map.ContainsKey(arr[i] - K))
    {
        maxDist = Math.Max(maxDist,
                            i - map[arr[i] - K]);
    }
    }
 
    // Return the answer
    if (maxDist == 0)
    return -1;
    else
    return maxDist;
}
 
// Driver Code
public static void Main(String []args)
{
    // Given array []arr
    int[] arr = { 11, 2, 3, 8, 5, 2 };
 
    // Given difference K
    int K = 2;
 
    // Function call
    Console.WriteLine(
    maxDistance(arr, K));
}
}
 
// This code is contributed by Princi Singh


Javascript


输出:
2

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

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