Open In App

Maximum difference between a pair of adjacent elements by excluding every element once

Last Updated : 15 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of positive integers, the task is to find the maximum difference between any two adjacent elements after excluding each element from the array (except the first and last elements).

Examples:

Input: arr[] = [1, 3, 4, 7, 8]
Output: [3, 4, 4]
Explanation:
Excluding i = 1: Remaining array = [1, 4, 7, 8] → Maximum adjacent difference = max(|4-1|, |7-4|, |8-7|) = 3
Excluding i = 2: Remaining array = [1, 3, 7, 8] → Maximum adjacent difference = max(|3-1|, |7-3|, |8-7|) = 4
Excluding i = 3: Remaining array = [1, 3, 4, 8] → Maximum adjacent difference = max(|3-1|, |4-3|, |8-4|) = 4

Input: arr[] = [1, 2, 7]
Output: [6]
Explanation: Excluding i = 1: Remaining array = [1, 7] → Maximum adjacent difference = |7-1| = 6

[Naive Approach] By Excluding Every Element - O(n^2) time and O(1) space

The simplest approach is to traverse the array and, for every element, calculate the difference between adjacent elements excluding that element, and return the overall maximum difference obtained.

C++
// C++ program to find maximum difference
// using naive approach 
#include <bits/stdc++.h>
using namespace std;

// Function to calculate maximum
// difference between adjacent elements
// excluding every array element once
vector<int> maxAdjacent(vector<int> &arr) {
  
    int n = arr.size();
    vector<int> 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);
    }

    return res;
}

int main() {

    vector<int> arr = {1, 3, 4, 7, 8};
    vector<int> res = maxAdjacent(arr);
    for (auto &i : res)
        cout << i << " ";
  	return 0;
}
Java
// Java program to find maximum difference
// using naive approach

import java.util.*;

class GfG {

    // Function to calculate maximum difference 
    // between adjacent elements
    // excluding every array element once
    static int[] maxAdjacent(int[] arr) {
      
        int n = arr.length;
        int[] res = new int[n - 2];

        // 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 an array
            res[i - 1] = maxi;
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 4, 7, 8};
        int[] res = maxAdjacent(arr);
        for (int i : res)
            System.out.print(i + " ");
    }
}
Python
# Python program to find maximum difference
# using naive approach

# Function to calculate maximum difference between adjacent elements
# excluding every array element once
def maxAdjacent(arr):
    n = len(arr)
    res = []

    # Traverse the array
    for i in range(1, n - 1):
        prev = arr[0]

        # Stores the maximum diff
        maxi = float('-inf')

        # Check for maximum adjacent element
        for j in range(1, n):

            # 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 list
        res.append(maxi)

    return res

arr = [1, 3, 4, 7, 8]
res = maxAdjacent(arr)
print(" ".join(map(str, res)))
C#
// C# program to find maximum difference
// using naive approach

using System;

class GfG {
  
    // Function to calculate maximum 
    // difference between adjacent elements
    // excluding every array element once
   static int[] MaxAdjacent(int[] arr) {
     
        int n = arr.Length;
        int[] res = new int[n - 2];

        // Traverse the array
        for (int i = 1; i < n - 1; i++) {
            int prev = arr[0];

            // Stores the maximum diff
            int maxi = int.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 an array
            res[i - 1] = maxi;
        }

        return res;
    }

    static void Main() {
        int[] arr = { 1, 3, 4, 7, 8 };
        int[] res = MaxAdjacent(arr);
        foreach (int i in res)
            Console.Write(i + " ");
    }
}
JavaScript
// JavaScript program to find maximum difference
// using naive approach

// Function to calculate maximum 
// difference between adjacent elements
// excluding every array element once
function maxAdjacent(arr) {
    const n = arr.length;
    const res = [];

    // Traverse the array
    for (let i = 1; i < n - 1; i++) {
        let prev = arr[0];

        // Stores the maximum diff
        let maxi = -Infinity;

        // Check for maximum adjacent element
        for (let 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 list
        res.push(maxi);
    }

    return res;
}

// Driver Code
const arr = [1, 3, 4, 7, 8];
const res = maxAdjacent(arr);
console.log(res.join(" "));

Output
3 4 4 

Time Complexity: O(n^2)
Space Complexity: O(1)

[Expected Approach] Using Single Traversal - O(n) Time and O(1) Space

It can be clearly observed that if an element is excluded from the array, then the maximum difference either remains the same or will become equal to the difference between the next and previous of the excluded element.

  • To calculate the maximum difference between adjacent elements in an array while excluding each element once, traverse the array and for each excluded element, compute the difference between the previous element and the one immediately following the excluded element.
  • Compare this difference with the maximum adjacent difference for the whole array. If the indices of maximum difference do not match with current index, insert the difference, else check for second maximum and similarly if indices are same insert max third maximum and current.
C++
// C++ program to find maximum difference
// using optimal  approach

#include <bits/stdc++.h>
using namespace std;

// Function to calculate maximum
// difference between adjacent elements
// excluding every array element once
vector<int> maxAdjacent(vector<int> &arr) {
  
    int n=arr.size();
    if(n < 3) return {};
    if(n == 3) return {abs(arr[0] - arr[2])};

    vector<int> res;

    // Find three maximum differences
    priority_queue<vector<int>> pq;
    for(int i = 1; i<n; i++) {
        int diff = abs(arr[i] - arr[i-1]);
        pq.push({diff, i-1, i});
        if(pq.size() > 3) pq.pop();
    }

    vector<vector<int>> maxThree;
    while(!pq.empty()) {
        maxThree.push_back(pq.top());
        pq.pop();
    }

    for (int i = 1; i < n - 1; i++) {

        int currMax = abs(arr[i - 1]
                           - arr[i + 1]);

        if(currMax >= maxThree[0][0]) {
            res.push_back(currMax);
        }
        else if(i != maxThree[0][1] && i != maxThree[0][2]) {
            res.push_back(maxThree[0][0]);
        }
        else if(currMax >= maxThree[1][0]) {
            res.push_back(currMax);
        }
        else if(i != maxThree[1][1] && i != maxThree[1][2]) {
            res.push_back(maxThree[1][0]);
        }
        else {
            res.push_back(max(currMax, maxThree[2][0]));
        }
    }

    return res;
}

int main() {
  
    vector<int> arr = { 1, 3, 4, 7, 8 };
    
    vector<int> res = maxAdjacent(arr);
    
     for(auto &i: res)
       cout<<i<<" ";
     
}
Java
// Java program to find maximum difference
// using optimal approach
import java.util.*;

class GfG {

    // Function to calculate maximum
    // difference between adjacent elements
    // excluding every array element once
    static int[] maxAdjacent(int[] arr) {
        
        int n = arr.length;
        if (n < 3) return new int[0];
        if (n == 3) return new int[]{Math.abs(arr[0] - arr[2])};

        int[] res = new int[n - 2];

        // Find three maximum differences
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]);
        for (int i = 1; i < n; i++) {
            int diff = Math.abs(arr[i] - arr[i - 1]);
            pq.offer(new int[]{diff, i - 1, i});
            if (pq.size() > 3) pq.poll();
        }

        int[][] maxThree = new int[3][];
        for (int i = 2; i >= 0 && !pq.isEmpty(); i--) {
            maxThree[i] = pq.poll();
        }

        for (int i = 1; i < n - 1; i++) {

            int currMax = Math.abs(arr[i - 1] - arr[i + 1]);

            if (currMax >= maxThree[0][0]) {
                res[i - 1] = currMax;
            } else if (i != maxThree[0][1] && i != maxThree[0][2]) {
                res[i - 1] = maxThree[0][0];
            } else if (currMax >= maxThree[1][0]) {
                res[i - 1] = currMax;
            } else if (i != maxThree[1][1] && i != maxThree[1][2]) {
                res[i - 1] = maxThree[1][0];
            } else {
                res[i - 1] = Math.max(currMax, maxThree[2][0]);
            }
        }

        return res;
    }

    public static void main(String[] args) {

        int[] arr = {1, 3, 4, 7, 8};

        int[] res = maxAdjacent(arr);

        for (int i : res) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python program to find maximum difference
# using optimal approach
import heapq

# Function to calculate maximum
# difference between adjacent elements
# excluding every array element once
def maxAdjacent(arr):
    n = len(arr)
    if n < 3:
        return []
    if n == 3:
        return [abs(arr[0] - arr[2])]

    res = []

    # Find three maximum differences
    pq = []
    for i in range(1, n):
        diff = abs(arr[i] - arr[i - 1])
        heapq.heappush(pq, (-diff, i - 1, i))
        if len(pq) > 3:
            heapq.heappop(pq)

    maxThree = []
    while pq:
        maxThree.append(heapq.heappop(pq))
    maxThree = [(-x[0], x[1], x[2]) for x in maxThree] 

    for i in range(1, n - 1):
        currMax = abs(arr[i - 1] - arr[i + 1])

        if currMax >= maxThree[0][0]:
            res.append(currMax)
        elif i != maxThree[0][1] and i != maxThree[0][2]:
            res.append(maxThree[0][0])
        elif currMax >= maxThree[1][0]:
            res.append(currMax)
        elif i != maxThree[1][1] and i != maxThree[1][2]:
            res.append(maxThree[1][0])
        else:
            res.append(max(currMax, maxThree[2][0]))

    return res


if __name__ == "__main__":
    arr = [1, 3, 4, 7, 8]
    res = maxAdjacent(arr)

    for i in res:
        print(i, end=" ")
C#
// C# program to find maximum difference
// using optimal approach
using System;
using System.Collections.Generic;
using System.Linq;

class GfG {

    // Function to calculate maximum
    // difference between adjacent elements
    // excluding every array element once
    static List<int> maxAdjacent(List<int> arr) {

        int n = arr.Count;
        if (n < 3) return new List<int>();
        if (n == 3) return new List<int> { Math.Abs(arr[0] - arr[2]) };

        List<int> res = new List<int>();

        // Find three maximum differences and their indices
        List<int[]> maxThree = FindThreeMaxDifferences(arr);

        for (int i = 1; i < n - 1; i++) {

            int currMax = Math.Abs(arr[i - 1] - arr[i + 1]);

            if (currMax >= maxThree[0][0]) {
                res.Add(currMax);
            } else if (i != maxThree[0][1] && i != maxThree[0][2]) {
                res.Add(maxThree[0][0]);
            } else if (currMax >= maxThree[1][0]) {
                res.Add(currMax);
            } else if (i != maxThree[1][1] && i != maxThree[1][2]) {
                res.Add(maxThree[1][0]);
            } else {
                res.Add(Math.Max(currMax, maxThree[2][0]));
            }
        }

        return res;
    }

    // Function to find the three maximum differences and their indices
    static List<int[]> FindThreeMaxDifferences(List<int> arr) {
        List<int[]> differences = new List<int[]>();

        for (int i = 1; i < arr.Count; i++) {
            int diff = Math.Abs(arr[i] - arr[i - 1]);
            differences.Add(new int[] { diff, i - 1, i });
        }

        // Sort differences in descending order
        differences.Sort((a, b) => b[0].CompareTo(a[0]));

        // Return the top three maximum differences
        return differences.Take(3).ToList();
    }

    static void Main(string[] args) {

        List<int> arr = new List<int> { 1, 3, 4, 7, 8 };

        List<int> res = maxAdjacent(arr);

        foreach (int i in res) {
            Console.Write(i + " ");
        }
    }
}
JavaScript
// JavaScript program to find maximum difference
// using optimal approach

// Function to calculate maximum
// difference between adjacent elements
// excluding every array element once
function maxAdjacent(arr) {

    let n = arr.length;
    if (n < 3) return [];
    if (n == 3) return [Math.abs(arr[0] - arr[2])];

    let res = [];

    // Find three maximum differences
    let pq = [];
    for (let i = 1; i < n; i++) {
        let diff = Math.abs(arr[i] - arr[i - 1]);
        pq.push([diff, i - 1, i]);
        pq.sort((a, b) => b[0] - a[0]);
        if (pq.length > 3) pq.pop();
    }

    let maxThree = pq.slice();

    for (let i = 1; i < n - 1; i++) {

        let currMax = Math.abs(arr[i - 1] - arr[i + 1]);

        if (currMax >= maxThree[0][0]) {
            res.push(currMax);
        } else if (i != maxThree[0][1] && i != maxThree[0][2]) {
            res.push(maxThree[0][0]);
        } else if (currMax >= maxThree[1][0]) {
            res.push(currMax);
        } else if (i != maxThree[1][1] && i != maxThree[1][2]) {
            res.push(maxThree[1][0]);
        } else {
            res.push(Math.max(currMax, maxThree[2][0]));
        }
    }

    return res;
}

// Example usage
let arr = [1, 3, 4, 7, 8];
let res = maxAdjacent(arr);
console.log(res.join(" "));

Output
3 4 4

Time Complexity: O(n)
Space Complexity: O(1)


Next Article

Similar Reads