Open In App

Largest gap in an array

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an unsorted array of length N, and we have to find the largest gap between any two elements of the array. In simple words, find max(|Ai-Aj|) where 1 ? i ? N and 1 ? j ? N.

Examples:  

Input : arr = {3, 10, 6, 7}
Output : 7
Explanation :
Here, we can see largest gap can be
found between 3 and 10 which is 7

Input : arr = {-3, -1, 6, 7, 0}
Output : 10
Explanation :
Here, we can see largest gap can be 
found between -3 and 7 which is 10 

Simple Approach: 

A simple solution is, we can use a naive approach. We will check the absolute difference of every pair in the array, and we will find the maximum value of it. So we will run two loops one is for i and one is for j complexity of this method is O(N^2)  

Implementation:

C++




// A C++ program to find largest gap
// between two elements in an array.
#include<bits/stdc++.h>
using namespace std;
 
// function to solve the given problem
int solve(int a[], int n)
{
    int max1 = INT_MIN;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (abs(a[i] - a[j]) > max1)
            {
                max1 = abs(a[i] - a[j]);
            }
        }
    }
    return max1;
}
 
// Driver Code
int main()
{
    int arr[] = { -1, 2, 3, -4, -10, 22 };
    int size = sizeof(arr) / sizeof(arr[0]);
    cout << "Largest gap is : "
         << solve(arr, size);
    return 0;
}
 
// This code is contributed
// by Akanksha Rai


C




// A C program to find largest gap
// between two elements in an array.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
 
// function to solve the given problem
int solve(int a[], int n)
{
    int max1 = INT_MIN;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (abs(a[i] - a[j]) > max1) {
                max1 = abs(a[i] - a[j]);
            }
        }
    }
    return max1;
}
 
int main()
{
    int arr[] = { -1, 2, 3, -4, -10, 22 };
    int size = sizeof(arr) / sizeof(arr[0]);
    printf("Largest gap is : %d", solve(arr, size));
    return 0;
}


Java




// A Java program to find
// largest gap between
// two elements in an array.
import java .io.*;
 
class GFG
{
 
// function to solve
// the given problem
static int solve(int []a,
                 int n)
{
    int max1 = Integer.MIN_VALUE ;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (Math.abs(a[i] -
                         a[j]) > max1)
            {
                max1 = Math.abs(a[i] -
                                a[j]);
            }
        }
    }
    return max1;
}
 
// Driver Code
static public void main (String[] args)
{
    int []arr = {-1, 2, 3,
                 -4, -10, 22};
    int size = arr.length;
    System.out.println("Largest gap is : " +
                        solve(arr, size));
}
}
 
// This code is contributed
// by anuj_67.


Python3




# A Python 3 program to find largest gap
# between two elements in an array.
import sys
 
# function to solve the given problem
def solve(a, n):
    max1 = -sys.maxsize - 1
    for i in range(0, n, 1):
        for j in range(0, n, 1):
            if (abs(a[i] - a[j]) > max1):
                max1 = abs(a[i] - a[j])
 
    return max1
 
# Driver Code
if __name__ == '__main__':
    arr = [-1, 2, 3, -4, -10, 22]
    size = len(arr)
    print("Largest gap is :", solve(arr, size))
 
# This code is contributed by
# Sanjit_Prasad


C#




// A C# program to find
// largest gap between
// two elements in an array.
using System;
 
class GFG
{
 
// function to solve
// the given problem
static int solve(int []a,
                 int n)
{
    int max1 = int.MinValue ;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (Math.Abs(a[i] -
                         a[j]) > max1)
            {
                max1 = Math.Abs(a[i] -
                                a[j]);
            }
        }
    }
    return max1;
}
 
// Driver Code
static public void Main ()
{
    int []arr = {-1, 2, 3,
                 -4, -10, 22};
    int size = arr.Length;
    Console.WriteLine("Largest gap is : " +
                         solve(arr, size));
}
}
 
// This code is contributed
// by anuj_67.


PHP




<?php
// A PHP program to find
// largest gap between
// two elements in an array.
 
// function to solve
// the given problem
function solve($a, $n)
{
    $max1 = PHP_INT_MIN;
    for ($i = 0; $i < $n; $i++)
    {
        for ($j = 0; $j < $n; $j++)
        {
            if (abs($a[$i] -
                    $a[$j]) > $max1)
            {
                $max1 = abs($a[$i] -
                            $a[$j]);
            }
        }
    }
    return $max1;
}
 
// Driver Code
$arr = array(-1, 2, 3,
             -4, -10, 22);
$size = count($arr);
echo "Largest gap is : ",
      solve($arr, $size);
 
// This code is contributed
// by anuj_67.
?>


Javascript




<script>
 
// A Javascript program to find
// largest gap between
// two elements in an array.
     
    // function to solve
// the given problem
    function solve(a,n)
    {
        let max1 = Number.MIN_VALUE ;
         
    for (let i = 0; i < n; i++)
    {
        for (let j = 0; j < n; j++)
        {
            if (Math.abs(a[i] - a[j]) > max1)
            {
                 
                max1 = Math.abs(a[i] - a[j]);
            }
        }
    }
    return max1;
    }
     
    // Driver Code
    let arr=[-1, 2, 3,
                 -4, -10, 22];
    let size = arr.length;
    document.write("Largest gap is : " +
                         solve(arr, size));
     
     
    // This code is contributed by rag2127
     
</script>


Output

Largest gap is : 32

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

Better Approach: 

Now we will see a better approach it is a greedy approach that can solve this problem in O(N). We will find the maximum and minimum element of the array which can be done in O(N) and then we will return the value of (maximum-minimum).  

Implementation:

C++




// A C++ program to find largest gap between
// two elements in an array.
#include<bits/stdc++.h>
using namespace std;
 
// function to solve the given problem
int solve(int a[], int n)
{
    int min1 = a[0];
    int max1 = a[0];
 
    // finding maximum and minimum of an array
    for (int i = 0; i < n; i++)
    {
        if (a[i] > max1)
            max1 = a[i];
        if (a[i] < min1)
            min1 = a[i];
    }
    return abs(min1 - max1);
}
 
// Driver code
int main()
{
    int arr[] = { -1, 2, 3, 4, -10 };
    int size = sizeof(arr) / sizeof(arr[0]);
    cout << "Largest gap is : " << solve(arr, size);
    return 0;
}
 
//This code is contributed by Mukul Singh.


C




// A C program to find largest gap between
// two elements in an array.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
 
// function to solve the given problem
int solve(int a[], int n)
{
    int min1 = a[0];
    int max1 = a[0];
 
    // finding maximum and minimum of an array
    for (int i = 0; i < n; i++) {
        if (a[i] > max1)
            max1 = a[i];
        if (a[i] < min1)
            min1 = a[i];
    }
     
    return abs(min1 - max1);
}
 
int main()
{
    int arr[] = { -1, 2, 3, 4, -10 };
    int size = sizeof(arr) / sizeof(arr[0]);
    printf("Largest gap is : %d", solve(arr, size));
    return 0;
}


Java




// A Java program to find largest gap
// between two elements in an array.
import java.io.*;
 
class GFG {
 
    // function to solve the given
    // problem
    static int solve(int a[], int n)
    {
        int min1 = a[0];
        int max1 = a[0];
     
        // finding maximum and minimum
        // of an array
        for (int i = 0; i < n; i++)
        {
            if (a[i] > max1)
                max1 = a[i];
            if (a[i] < min1)
                min1 = a[i];
        }
         
        return Math.abs(min1 - max1);
    }
 
    // Driver code
    public static void main (String[] args)
    {
        int []arr = { -1, 2, 3, 4, -10 };
        int size = arr.length;
        System.out.println("Largest gap is : "
                         + solve(arr, size));
    }
}
 
// This code is contributed by anuj_67.


Python3




# A python 3 program to find largest gap between
# two elements in an array.
  
# function to solve the given problem
def solve(a,  n):
 
    min1 = a[0]
    max1 = a[0]
  
    # finding maximum and minimum of an array
    for i in range ( n):
     
        if (a[i] > max1):
            max1 = a[i]
        if (a[i] < min1):
            min1 = a[i]
     
    return abs(min1 - max1)
 
# Driver code
if __name__ == "__main__":
 
    arr = [ -1, 2, 3, 4, -10 ]
    size = len(arr)
    print("Largest gap is : " ,solve(arr, size))
 
# This code is contributed by chitranayal 


C#




// A C# program to find
// largest gap between
// two elements in an array.
using System;
 
class GFG
{
 
    // function to solve
    // the given problem
    static int solve(int []a,
                     int n)
    {
        int min1 = a[0];
        int max1 = a[0];
     
        // finding maximum and
        // minimum of an array
        for (int i = 0; i < n; i++)
        {
            if (a[i] > max1)
                max1 = a[i];
            if (a[i] < min1)
                min1 = a[i];
        }
         
        return Math.Abs(min1 -
                        max1);
    }
 
    // Driver code
    public static void Main ()
    {
        int []arr = {-1, 2, 3, 4, -10};
        int size = arr.Length;
        Console.WriteLine("Largest gap is : " +
                             solve(arr, size));
    }
}
 
// This code is contributed
// by anuj_67.


PHP




<?php
// A PHP program to find
// largest gap between
// two elements in an array.
 
// function to solve
// the given problem
function solve($a, $n)
{
    $min1 = $a[0];
    $max1 = $a[0];
 
    // finding maximum and
    // minimum of an array
    for ($i = 0; $i < $n; $i++)
    {
        if ($a[$i] > $max1)
            $max1 = $a[$i];
        if ($a[$i] < $min1)
            $min1 = $a[$i];
    }
     
    return abs($min1 - $max1);
}
 
// Driver Code
$arr = array(-1, 2, 3, 4, -10);
$size = count($arr);
echo "Largest gap is : ",
      solve($arr, $size);
 
// This code is contributed
// by anuj_67.
?>


Javascript




<script>
// A Javascript program to find largest gap
// between two elements in an array.
     
    // function to solve the given
    // problem
    function solve(a,n)
    {
        let min1 = a[0];
        let max1 = a[0];
      
        // finding maximum and minimum
        // of an array
        for (let i = 0; i < n; i++)
        {
            if (a[i] > max1)
                max1 = a[i];
            if (a[i] < min1)
                min1 = a[i];
        }
          
        return Math.abs(min1 - max1);
    }
     
     // Driver code
    let arr=[-1, 2, 3, 4, -10 ];
    let size = arr.length;
    document.write("Largest gap is : "
                         + solve(arr, size));
     
     
 
// This code is contributed by avanitrachhadiya2155
</script>


Output

Largest gap is : 14


Previous Article
Next Article

Similar Reads

Sort a nearly sorted (or K sorted) array | Set 2 (Gap method - Shell sort)
Given an array, arr[] of N elements, where each element is at most K away from its target position, the task is to devise an algorithm that sorts in O(N*log(K)) time. Examples: Input: arr[] = {10, 9, 8, 7, 4, 70, 60, 50}, K = 4Output: 4 7 8 9 10 50 60 70Explanation:Follow the steps below to sort the array: Start with Gap = K(i.e. 4)10 9 8 7 4 70 60
8 min read
Gap Buffer Data Structure
INTRODUCTION: Gap Buffer is a data structure for the dynamic insertion and deletion of elements in a buffer or an array. It represents a buffer or an array as a gap surrounded by two pointers, one pointing to the beginning of the buffer and the other pointing to the end. When elements are inserted or deleted, the gap is moved to accommodate the cha
17 min read
Gap Buffer | Deletion Operation
We have discussed Gap buffer and insert operations. In this post, delete operation is discussed. When we want to delete a character these three cases may arise. Characters to be deleted is at cursor position: Let's assume we want to delete "FOR" from "FORGEEKS", since the cursor (gap_left) is at desired position the character is deleted i.e. the ga
12 min read
Rearrange an array in order - smallest, largest, 2nd smallest, 2nd largest, ..
Given an array of integers, the task is to print the array in the order - smallest number, the Largest number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number, and so on..... Examples: Input : arr[] = [5, 8, 1, 4, 2, 9, 3, 7, 6] Output :arr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5} Input : arr[] = [1, 2, 3, 4] Output :arr[] =
7 min read
Find the largest and second largest value in a Linked List
Given a Linked List, the task is to find the largest and second largest value in a Linked List.Example: Input: LL = 10 -&gt; 15 -&gt; 5 -&gt; 20 -&gt; 7 -&gt; 9 Output: Largest = 20 Second Largest = 15Input: LL = 0 -&gt; 5 -&gt; 52 -&gt; 21 Output: Largest = 52 Second Largest = 21 Approach: Store the maximum of first two nodes in a variable max.Sto
9 min read
Count of subarrays with largest element at least twice the largest of remaining elements
Given an array arr[] consisting of N positive integers, the task is to find the count of subarrays such that the maximum element of the subarray is greater than twice the maximum of all other elements of the array. Examples: Input: arr[] = {1, 6, 10, 9, 7, 3}Output: 4Explanation:Below are the subarrays satisfying the given condition: Consider the s
14 min read
Find Array formed by adding each element of given array with largest element in new array to its left
Given an array A of size N, the task is to find the resultant array formed by adding each element of the given array with the largest element in the new array to its left.Examples: Input: arr[] = {5, 1, 6, -3, 2} Output: {5, 6, 12, 9, 14} Element A0: No element if present at its left. Hence the element at 0th index of the resultant array = 5 Elemen
6 min read
Array formed from difference of each element from the largest element in the given array
Given an array arr[], the task is to find the array formed from the difference of each element from the largest element in the given array. Example: Input: arr[] = {3, 6, 9, 2,6} Output: {6, 3, 0, 7, 3} Explanation: Largest element of the array = 9 Therefore difference of arr[i] from 9: Element 1: 9 - 3 = 6 Element 2: 9 - 6 = 3 Element 3: 9 - 9 = 0
5 min read
Mean of given array after removal of K percent of smallest and largest array elements
Given an array arr[] and an integer K, the task is to remove K % percent array elements from the smallest and largest array elements and calculate the mean of the remaining array. Examples: Input: arr[] = {6, 2, 7, 5, 1, 2, 0, 3, 10, 2, 5, 0, 5, 5, 0, 8, 7, 6, 8, 0}, K = 5Output: 4.00000Explanation:There are 20 elements in the array. Therefore, 5%
6 min read
Minimize swaps required to place largest and smallest array elements at first and last array indices
Given an array arr[] of size N, the task is to find the minimum count of adjacent swaps required to rearrange the array elements such that the largest and the smallest array element present on the first and the last indices of the array respectively. Examples: Input: arr[] = {33, 44, 11, 12} Output: 2 Explanation: Swapping the pair (arr[0], arr[1])
8 min read
Practice Tags :