Maximum difference between a pair of adjacent elements by excluding every element once
Last Updated :
15 Feb, 2025
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(" "));
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(" "));
Time Complexity: O(n)
Space Complexity: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read