Subarray with difference between maximum and minimum element greater than or equal to its length
Last Updated :
31 May, 2021
Given an array arr[], the task is to find a subarray with the difference between the maximum and the minimum element is greater than or equal to the length of subarray. If no such subarray exists then print -1.
Examples:
Input: arr[] = {3, 7, 5, 1}
Output: 3 7
|3 – 7| > length({3, 7}) i.e. 4 ≥ 2
Input: arr[] = {1, 2, 3, 4, 5}
Output: -1
There is no such subarray that meets the criteria.
Naive approach: Find All the subarray that are possible with at least two elements and then check for each of the subarrays that satisfy the given condition i.e. max(subarray) – min(subarray) ≥ len(subarray)
Efficient approach: Find the subarrays of length 2 where the absolute difference between the only two elements is greater than or equal to 2. This will cover almost all the cases because there are only three cases when there is no such subarray:
- When the length of the array is 0.
- When all the elements in the array are equal.
- When every two consecutive elements in the array have an absolute difference of either 0 or 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findSubArr( int arr[], int n)
{
for ( int i = 0; i < n - 1; i++) {
if ( abs (arr[i] - arr[i + 1]) >= 2) {
cout << arr[i] << " " << arr[i + 1];
return ;
}
}
cout << -1;
}
int main()
{
int arr[] = { 1, 2, 4, 6, 7 };
int n = sizeof (arr) / sizeof ( int );
findSubArr(arr, n);
return 0;
}
|
Java
class GFG
{
static void findSubArr( int arr[], int n)
{
for ( int i = 0 ; i < n - 1 ; i++)
{
if (Math.abs(arr[i] - arr[i + 1 ]) >= 2 )
{
System.out.print(arr[i] + " " + arr[i + 1 ]);
return ;
}
}
System.out.print(- 1 );
}
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 4 , 6 , 7 };
int n = arr.length;
findSubArr(arr, n);
}
}
|
Python3
def findSubArr(arr, n) :
for i in range (n - 1 ) :
if ( abs (arr[i] - arr[i + 1 ]) > = 2 ) :
print (arr[i] ,arr[i + 1 ],end = "");
return ;
print ( - 1 );
if __name__ = = "__main__" :
arr = [ 1 , 2 , 4 , 6 , 7 ];
n = len (arr);
findSubArr(arr, n);
|
C#
using System;
class GFG
{
static void findSubArr( int []arr, int n)
{
for ( int i = 0; i < n - 1; i++)
{
if (Math.Abs(arr[i] - arr[i + 1]) >= 2)
{
Console.Write(arr[i] + " " + arr[i + 1]);
return ;
}
}
Console.Write(-1);
}
public static void Main()
{
int []arr = { 1, 2, 4, 6, 7 };
int n = arr.Length;
findSubArr(arr, n);
}
}
|
Javascript
<script>
function findSubArr(arr, n) {
for (let i = 0; i < n - 1; i++) {
if (Math.abs(arr[i] - arr[i + 1]) >= 2) {
document.write(arr[i] + " " + arr[i + 1]);
return ;
}
}
document.write(-1);
}
let arr = [1, 2, 4, 6, 7];
let n = arr.length
findSubArr(arr, n);
</script>
|
Time Complexity: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...