Maximum difference between first and last indexes of an element in array
Last Updated :
12 Jul, 2022
Given an array of n integers. The task is to find the difference of first and last index of each distinct element so as to maximize the difference.
Examples:
Input : {2, 1, 3, 4, 2, 1, 5, 1, 7}
Output : 6
Element 1 has its first index = 1
and last index = 7
Difference = 7 - 1 = 6
Other elements have a smaller first and last
index difference
Input : {2, 2, 1, 1, 8, 8, 3, 5, 3}
Output : 2
Maximum difference is for indexes of element 3.
A simple approach is to run two loops and find the difference for each element and accordingly update the max_diff. It has a time complexity of O(n2) and the approach also needs to keep track of the elements that have been visited so that difference for them is not calculated unnecessarily.
An efficient approach uses hashing. It has the following steps.
- Traverse the input array from left to right.
- For each distinct element map its first and last index in the hash table.
- Traverse the hash table and calculate the first and last index difference for each element.
- Accordingly update the max_diff.
In the following implementation unordered_map has been used for hashing as the range of integers is not known.
C++
// C++ implementation to find the maximum difference
// of first and last index of array elements
#include <bits/stdc++.h>
using namespace std;
// function to find the
// maximum difference
int maxDifference(int arr[], int n)
{
// structure to store first and last
// index of each distinct element
struct index
{
int f, l;
};
// maps each element to its
// 'index' structure
unordered_map<int, index> um;
for (int i=0; i<n; i++)
{
// storing first index
if (um.find(arr[i]) == um.end())
um[arr[i]].f = i;
// storing last index
um[arr[i]].l = i;
}
int diff, max_diff = INT_MIN;
unordered_map<int, index>::iterator itr;
// traversing 'um'
for (itr=um.begin(); itr != um.end(); itr++)
{
// difference of last and first index
// of each element
diff = (itr->second).l - (itr->second).f;
// update 'max_dff'
if (max_diff < diff)
max_diff = diff;
}
// required maximum difference
return max_diff;
}
// Driver program to test above
int main()
{
int arr[] = {2, 1, 3, 4, 2, 1, 5, 1, 7};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum Difference = "
<<maxDifference(arr, n);
return 0;
}
Java
// Java implementation to find the maximum difference
// of first and last index of array elements
import java.util.HashMap;
import java.util.Map;
public class MaxDiffIndexHashing {
static class Element {
int first;
int second;
public Element() {
super();
}
public Element(int first, int second) {
super();
this.first = first;
this.second = second;
}
}
public static void main(String[] args) {
int arr[]={2, 1, 3, 4, 2, 1, 5, 1, 7};
System.out.println("Maximum Difference= "+ maxDiffIndices(arr));
}
private static int maxDiffIndices(int[] arr) {
int n = arr.length;
int maxDiffIndex = 0;
Map<Integer, Element> map = new HashMap<Integer, Element>();
for (int i = 0; i < n; i++) {
if (map.containsKey(arr[i])) {
Element e = map.get(arr[i]);
e.second = i;
} else {
Element e = new Element();
e.first = i;
map.put(arr[i], e);
}
}
for (Map.Entry<Integer, Element> entry : map.entrySet()) {
Element e = entry.getValue();
if ((e.second - e.first) > maxDiffIndex)
maxDiffIndex = e.second - e.first;
}
return maxDiffIndex;
}
}
Python3
# Python3 implementation to find the maximum difference
# of first and last index of array elements
# function to find the
# maximum difference
import sys
def maxDifference(arr, n):
# structure to store first and last
# index of each distinct element
class index:
def __init__(self,f,l):
self.f = f
self.l = l
# maps each element to its
# 'index' structure
um = {}
for i in range(n):
# storing last index
if (arr[i] in um):
e = um[arr[i]]
e.l = i
# storing first index
else:
e = index(i,i)
um[arr[i]] = e
diff = -sys.maxsize -1
max_diff = -sys.maxsize -1
# traversing 'um'
for key,value in um.items():
# difference of last and first index
# of each element
diff = value.l - value.f
# update 'max_dff'
if (max_diff < diff):
max_diff = diff
# required maximum difference
return max_diff
# Driver program to test above
arr = [2, 1, 3, 4, 2, 1, 5, 1, 7]
n = len(arr)
print(f"Maximum Difference = {maxDifference(arr, n)}")
# This code is contributed by shinjanpatra
C#
// C# implementation to find the maximum difference
// of first and last index of array elements
using System;
using System.Collections.Generic;
public class MaxDiffIndexHashing
{
class Element {
public int first;
public int second;
public Element() {
}
public Element(int first, int second) {
this.first = first;
this.second = second;
}
}
public static void Main(String[] args) {
int []arr={2, 1, 3, 4, 2, 1, 5, 1, 7};
Console.WriteLine("Maximum Difference= "+ maxDiffIndices(arr));
}
private static int maxDiffIndices(int[] arr) {
int n = arr.Length;
int maxDiffIndex = 0;
Dictionary<int, Element> map = new Dictionary<int, Element>();
for (int i = 0; i < n; i++) {
if (map.ContainsKey(arr[i])) {
Element e = map[arr[i]];
e.second = i;
} else {
Element e = new Element();
e.first = i;
map.Add(arr[i], e);
}
}
foreach(KeyValuePair<int, Element> entry in map) {
Element e = entry.Value;
if ((e.second - e.first) > maxDiffIndex)
maxDiffIndex = e.second - e.first;
}
return maxDiffIndex;
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript implementation to find the maximum difference
// of first and last index of array elements
// function to find the
// maximum difference
function maxDifference(arr, n)
{
// structure to store first and last
// index of each distinct element
class index
{
constructor(f,l){
this.f = f;
this.l = l;
}
};
// maps each element to its
// 'index' structure
let um = new Map();
for (let i=0; i<n; i++)
{
// storing last index
if (um.has(arr[i]) == true){
let e = um.get(arr[i]);
e.l = i;
}
// storing first index
else{
let e = new index();
e.f = i;
um.set(arr[i], e);
}
}
let diff, max_diff = Number.MIN_VALUE;
// traversing 'um'
for (let [key,value] of um)
{
// difference of last and first index
// of each element
diff = value.l - value.f;
// update 'max_dff'
if (max_diff < diff)
max_diff = diff;
}
// required maximum difference
return max_diff;
}
// Driver program to test above
let arr = [2, 1, 3, 4, 2, 1, 5, 1, 7];
let n = arr.length;
document.write("Maximum Difference = " +maxDifference(arr, n),"</br>");
// This code is contributed by shinjanpatra
</script>
OutputMaximum Difference = 6
Time Complexity: O(n)
Similar Reads
Maximum difference between two elements in an Array Given an array arr[] of N integers, the task is to find the maximum difference between any two elements of the array.Examples: Input: arr[] = {2, 1, 5, 3} Output: 4 |5 - 1| = 4 Input: arr[] = {-10, 4, -9, -5} Output: 14 Naive Approach:- As the maximum difference will be in between smallest and the l
9 min read
Maximum absolute difference between distinct elements in an Array Given an array arr[] of N integers, the task is to find the maximum absolute difference between distinct elements of the array.Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45, 10} Output: 10 Explanation: Distinct elements of given array are 12, 9, 2. Therefore, the maximum absolute difference
6 min read
Minimum distance between the maximum and minimum element of a given Array Given an array A[] consisting of N elements, the task is to find the minimum distance between the minimum and the maximum element of the array.Examples: Input: arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2} Output: 3 Explanation: The minimum element(= 1) is present at indices {2, 4} The maximum elemen
8 min read
Minimize difference between maximum and minimum array elements by removing a K-length subarray Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum difference between the maximum and minimum element present in the array after removing any subarray of size K. Examples: Input: arr[] = {4, 5, 8, 9, 1, 2}, K = 2Output: 4Explanation: Remove the subarray {
10 min read
Program to find the maximum difference between the index of any two different numbers Given an array of N integers. The task is to find the maximum difference between the index of any two different numbers. Note that there is a minimum of two different numbers. Examples: Input: a[] = {1, 2, 3, 2, 3} Output: 4 The difference between 1 and last 3.Input: a[] = {1, 1, 3, 1, 1, 1} Output:
5 min read
Maximum Difference between Two Elements such that Larger Element Appears after the Smaller Element Given an array of integers, the task is to find the maximum difference between any two elements such that larger element appears after the smaller number. We mainly need to find maximum difference in an inversion (larger before smaller)Note: If no such pair exists, return -1.Examples : Input : arr =
11 min read
Maximum in array which is at-least twice of other elements Given an array of integers of length n. Our task is to return the index of the max element if the it is at least twice as much as every other number in the array. If the max element does not satisfy the condition return -1. Examples: Input : arr = {3, 6, 1, 0} Output : 1 Here, 6 is the largest integ
7 min read
Maximum distance between i and j such that i ⤠j and A[i] ⤠B[j] Given two non-increasing arrays A[] and B[] of size N, the task is to find the maximum distance between i and j such that i ⤠j and A[i] ⤠B[j]. Examples: Input: A[] = {2, 2, 2}, B[] = {10, 10, 1}Output: 1Explanation: The valid pairs satisfying the conditions are (0, 0), (0, 1), and (1, 1).Therefore
11 min read
Find indices of all local maxima and local minima in an Array Given an array arr[] of integers. The task is to find the indices of all local minima and local maxima in the given array.Examples:Input: arr = [100, 180, 260, 310, 40, 535, 695]Output:Points of local minima: 0 4 Points of local maxima: 3 6Explanation:Given array can be break as below sub-arrays:1.
9 min read
Bitonic Point - Maximum in Increasing Decreasing Array Given an array arr[] of integers which is initially strictly increasing and then strictly decreasing, the task is to find the bitonic point, that is the maximum value in the array. Note: Bitonic Point is a point in bitonic sequence before which elements are strictly increasing and after which elemen
10 min read