📌  相关文章
📜  一对相邻元素之间的最大差值,将每个元素排除一次

📅  最后修改于: 2021-04-17 14:41:35             🧑  作者: Mango

给定一个由正整数组成的数组arr [] ,每个数组元素的任务是找出除该元素之外的任何两个相邻数组之间的最大差值。

例子:

天真的方法:最简单的方法是使用遍历数组,并对每个元素计算除该元素之外的相邻元素之间的差异,并打印获得的最大差异。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate maximum
// difference between adjacent elements
// excluding every array element once
void maxAdjacent(int* arr, int N)
{
    vector res;
 
    // Traverse the array
    for (int i = 1; i < N - 1; i++) {
 
        int prev = arr[0];
 
        // Stores the maximum diff
        int maxi = INT_MIN;
 
        // Check for maximum
        // adjacent element
        for (int j = 1; j < N; j++) {
 
            // Exclude current element
            if (i == j)
                continue;
 
            // Update maximum difference
            maxi = max(maxi, abs(arr[j] - prev));
 
            // Update previous value
            prev = arr[j];
        }
 
        // Append the result
        // into a vector
        res.push_back(maxi);
    }
 
    // Print the result
    for (auto x : res)
        cout << x << " ";
    cout << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 3, 4, 7, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    maxAdjacent(arr, N);
}


Java
// Java implementation of above approach 
import java.util.*;
class GFG
{
 
  // Function to calculate maximum
  // difference between adjacent elements
  // excluding every array element once
  static void maxAdjacent(int[] arr, int N)
  {
    ArrayList res = new ArrayList();
 
    // Traverse the array
    for (int i = 1; i < N - 1; i++)
    {
      int prev = arr[0];
 
      // Stores the maximum diff
      int maxi = Integer.MIN_VALUE;
 
      // Check for maximum
      // adjacent element
      for (int j = 1; j < N; j++)
      {
 
        // Exclude current element
        if (i == j)
          continue;
 
        // Update maximum difference
        maxi = Math.max(maxi, Math.abs(arr[j] - prev));
 
        // Update previous value
        prev = arr[j];
      }
 
      // Append the result
      // into a vector
      res.add(maxi);
    }
 
    // Print the result
    for (int x : res)
    {
      System.out.print(x + " ");
    }
    System.out.println();
  }
  // Driver code
  public static void main(String[] args)
  {
    int[] arr = { 1, 3, 4, 7, 8 };
    int N = arr.length;
    maxAdjacent(arr, N);
  }
}
 
// This code is contributed by sanjoy_62.


Python3
# Python program for the above approach
 
# Function to calculate maximum
# difference between adjacent elements
# excluding every array element once
def maxAdjacent(arr, N):
    res = []
 
    # Traverse the array
    for i in range(1, N - 1):
        prev = arr[0]
 
        # Stores the maximum diff
        maxi = -1* float('inf')
 
        # Check for maximum
        # adjacent element
        for j in range(1,N):
 
            # Exclude current element
            if (i == j):
                continue
 
            # pdate maximum difference
            maxi = max(maxi, abs(arr[j] - prev))
 
            # Update previous value
            prev = arr[j]
 
        # Append the result
        # into a vector
        res.append(maxi)
 
    # Print the result
    for x in res:
        print(x,end=' ')
    print()
 
# Driver Code
arr = [ 1, 3, 4, 7, 8 ]
N = len(arr)
maxAdjacent(arr, N)
 
# This code is contributed by rohitsingh07052.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG
{
   
  // Function to calculate maximum
  // difference between adjacent elements
  // excluding every array element once
  static void maxAdjacent(int[] arr, int N)
  {
    List res = new List();
 
    // Traverse the array
    for (int i = 1; i < N - 1; i++)
    {
      int prev = arr[0];
 
      // Stores the maximum diff
      int maxi = Int32.MinValue;
 
      // Check for maximum
      // adjacent element
      for (int j = 1; j < N; j++)
      {
 
        // Exclude current element
        if (i == j)
          continue;
 
        // Update maximum difference
        maxi = Math.Max(maxi, Math.Abs(arr[j] - prev));
 
        // Update previous value
        prev = arr[j];
      }
 
      // Append the result
      // into a vector
      res.Add(maxi);
    }
 
    // Print the result
    foreach (int x in res)
    {
      Console.Write(x + " ");
    }
    Console.WriteLine();
  }
 
// Driver Code
static public void Main ()
{
    int[] arr = { 1, 3, 4, 7, 8 };
    int N = arr.Length;
    maxAdjacent(arr, N);
}
}
 
// This code is contributed by code_hunt.


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to calculate maximum
// difference between adjacent elements
// excluding every array element once
void maxAdjacent(int* arr, int N)
{
    vector res;
 
    int arr_max = INT_MIN;
 
    // Compute maximum adjacent
    // difference for whole array
    for (int i = 1; i < N; i++) {
 
        arr_max = max(arr_max,
                      abs(arr[i - 1] - arr[i]));
    }
 
    for (int i = 1; i < N - 1; i++) {
 
        int curr_max = abs(arr[i - 1]
                           - arr[i + 1]);
 
        // Store the maximum between
        // arr_max and curr_max
        int ans = max(curr_max, arr_max);
 
        // Append the result
        // into a vector
        res.push_back(ans);
    }
 
    // Print the result
    for (auto x : res)
        cout << x << " ";
    cout << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 3, 4, 7, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    maxAdjacent(arr, N);
 
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
  // Function to calculate maximum
  // difference between adjacent elements
  // excluding every array element once
  static void maxAdjacent(int []arr, int N)
  {
    Vector res = new Vector();
    int arr_max = Integer.MIN_VALUE;
 
    // Compute maximum adjacent
    // difference for whole array
    for (int i = 1; i < N; i++)
    {
      arr_max = Math.max(arr_max,
                         Math.abs(arr[i - 1] - arr[i]));
    }
 
    for (int i = 1; i < N - 1; i++)
    {
      int curr_max = Math.abs(arr[i - 1]
                              - arr[i + 1]);
 
      // Store the maximum between
      // arr_max and curr_max
      int ans = Math.max(curr_max, arr_max);
 
      // Append the result
      // into a vector
      res.add(ans);
    }
 
    // Print the result
    for (int x : res)
      System.out.print(x + " ");
    System.out.println();
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = { 1, 3, 4, 7, 8 };
    int N = arr.length;
    maxAdjacent(arr, N);
  }
}
 
// This code is contributed by shikhasingrajput


Python3
# Python 3 program for the above approach
import sys
 
# Function to calculate maximum
# difference between adjacent elements
# excluding every array element once
def maxAdjacent(arr, N):
    res = []
    arr_max = -sys.maxsize - 1
 
    # Compute maximum adjacent
    # difference for whole array
    for i in range(1, N):
 
        arr_max = max(arr_max,
                      abs(arr[i - 1] - arr[i]))
    for i in range(1, N - 1):
        curr_max = abs(arr[i - 1]
                       - arr[i + 1])
 
        # Store the maximum between
        # arr_max and curr_max
        ans = max(curr_max, arr_max)
 
        # Append the result
        # into a vector
        res.append(ans)
 
    # Print the result
    for x in res:
        print(x, end=" ")
    print()
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 3, 4, 7, 8]
    N = len(arr)
    maxAdjacent(arr, N)
 
    # This code is contributed by chitranayal.


C#
// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
  // Function to calculate maximum
  // difference between adjacent elements
  // excluding every array element once
  static void maxAdjacent(int []arr, int N)
  {
    List res = new List();
    int arr_max = Int32.MinValue;
 
    // Compute maximum adjacent
    // difference for whole array
    for (int i = 1; i < N; i++)
    {
      arr_max = Math.Max(arr_max,
                         Math.Abs(arr[i - 1] - arr[i]));
    }
 
    for (int i = 1; i < N - 1; i++)
    {
      int curr_max = Math.Abs(arr[i - 1]
                              - arr[i + 1]);
 
      // Store the maximum between
      // arr_max and curr_max
      int ans = Math.Max(curr_max, arr_max);
 
      // Append the result
      // into a vector
      res.Add(ans);
    }
 
    // Print the result
    foreach (int x in res)
    Console.Write(x + " ");
    Console.WriteLine();
  }
 
// Driver Code
public static void Main(String[] args)
{
    int[] arr = { 1, 3, 4, 7, 8 };
    int N = arr.Length;
    maxAdjacent(arr, N);
}
}
 
// This code is contributed by susmitakundugoaldanga.


输出:
3 4 4

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

高效方法:可以清楚地观察到,如果从数组中排除某个元素,则最大差异要么保持不变,要么等于被排除元素的下一个和上一个元素之间的差异。请按照以下步骤解决问题:

  1. 计算数组中相邻元素之间的最大差。
  2. 遍历数组并执行以下操作:
    1. 评估前一个元素与排除元素旁边的数组元素之间的差异。
    2. 如果计算出的最大相邻差值超过了上一步获得的差值,则将整个数组的最大相邻差值插入向量res中
    3. 否则,将前一个元素和数组元素之间的差值插入到向量res中,将被排除元素旁边的元素插入数组中。
  3. 打印矢量res

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to calculate maximum
// difference between adjacent elements
// excluding every array element once
void maxAdjacent(int* arr, int N)
{
    vector res;
 
    int arr_max = INT_MIN;
 
    // Compute maximum adjacent
    // difference for whole array
    for (int i = 1; i < N; i++) {
 
        arr_max = max(arr_max,
                      abs(arr[i - 1] - arr[i]));
    }
 
    for (int i = 1; i < N - 1; i++) {
 
        int curr_max = abs(arr[i - 1]
                           - arr[i + 1]);
 
        // Store the maximum between
        // arr_max and curr_max
        int ans = max(curr_max, arr_max);
 
        // Append the result
        // into a vector
        res.push_back(ans);
    }
 
    // Print the result
    for (auto x : res)
        cout << x << " ";
    cout << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 3, 4, 7, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    maxAdjacent(arr, N);
 
}

Java

// Java program for the above approach
import java.util.*;
class GFG
{
 
  // Function to calculate maximum
  // difference between adjacent elements
  // excluding every array element once
  static void maxAdjacent(int []arr, int N)
  {
    Vector res = new Vector();
    int arr_max = Integer.MIN_VALUE;
 
    // Compute maximum adjacent
    // difference for whole array
    for (int i = 1; i < N; i++)
    {
      arr_max = Math.max(arr_max,
                         Math.abs(arr[i - 1] - arr[i]));
    }
 
    for (int i = 1; i < N - 1; i++)
    {
      int curr_max = Math.abs(arr[i - 1]
                              - arr[i + 1]);
 
      // Store the maximum between
      // arr_max and curr_max
      int ans = Math.max(curr_max, arr_max);
 
      // Append the result
      // into a vector
      res.add(ans);
    }
 
    // Print the result
    for (int x : res)
      System.out.print(x + " ");
    System.out.println();
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[] = { 1, 3, 4, 7, 8 };
    int N = arr.length;
    maxAdjacent(arr, N);
  }
}
 
// This code is contributed by shikhasingrajput

Python3

# Python 3 program for the above approach
import sys
 
# Function to calculate maximum
# difference between adjacent elements
# excluding every array element once
def maxAdjacent(arr, N):
    res = []
    arr_max = -sys.maxsize - 1
 
    # Compute maximum adjacent
    # difference for whole array
    for i in range(1, N):
 
        arr_max = max(arr_max,
                      abs(arr[i - 1] - arr[i]))
    for i in range(1, N - 1):
        curr_max = abs(arr[i - 1]
                       - arr[i + 1])
 
        # Store the maximum between
        # arr_max and curr_max
        ans = max(curr_max, arr_max)
 
        # Append the result
        # into a vector
        res.append(ans)
 
    # Print the result
    for x in res:
        print(x, end=" ")
    print()
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 3, 4, 7, 8]
    N = len(arr)
    maxAdjacent(arr, N)
 
    # This code is contributed by chitranayal.

C#

// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
  // Function to calculate maximum
  // difference between adjacent elements
  // excluding every array element once
  static void maxAdjacent(int []arr, int N)
  {
    List res = new List();
    int arr_max = Int32.MinValue;
 
    // Compute maximum adjacent
    // difference for whole array
    for (int i = 1; i < N; i++)
    {
      arr_max = Math.Max(arr_max,
                         Math.Abs(arr[i - 1] - arr[i]));
    }
 
    for (int i = 1; i < N - 1; i++)
    {
      int curr_max = Math.Abs(arr[i - 1]
                              - arr[i + 1]);
 
      // Store the maximum between
      // arr_max and curr_max
      int ans = Math.Max(curr_max, arr_max);
 
      // Append the result
      // into a vector
      res.Add(ans);
    }
 
    // Print the result
    foreach (int x in res)
    Console.Write(x + " ");
    Console.WriteLine();
  }
 
// Driver Code
public static void Main(String[] args)
{
    int[] arr = { 1, 3, 4, 7, 8 };
    int N = arr.Length;
    maxAdjacent(arr, N);
}
}
 
// This code is contributed by susmitakundugoaldanga.

 

输出:
3 4 4

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