Open In App

Min and max length subarray having adjacent element difference atmost K

Last Updated : 25 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] and an integer K, the task is to find the maximum and minimum length subarray such that the difference between adjacent elements is at most K.
Examples: 
 

Input: arr[] = {2, 4, 6}, K = 2 
Output: 3, 3 
Explanation: 
Minimum and Maximum length subarray such that difference 
between adjacent elements is at most is 3, which is {2, 4, 2}
Input: arr[] = {2, 3, 6, 7, 8}, K = 2 
Output: 2, 3 
Explanation: 
Minimum length Subarray(2) => {2, 3} 
Maximum length Subarray(3) => {6, 7, 8} 
 

 

Approach: The idea is traverse the array, to start from each element and move to its right and left direction until the difference between the adjacent elements is less than K. Finally, update the maximum and minimum length subarray with the current length as defined below – 
 

if (current_length  maximum_length)
   maximum_length = current_length

Below is the implementation of the above approach:
 

C++




// C++ program to find the minimum
// and maximum length subarray such
// that difference between adjacent
// elements is atmost K
 
#include <iostream>
 
using namespace std;
 
// Function to find the maximum and
// minimum length subarray
void findMaxMinSubArray(int arr[],
                        int K, int n)
{
    // Initialise minimum and maximum
    // size of subarray in worst case
    int min = n;
    int max = 0;
 
    // Left will scan the size of
    // possible subarray in left
    // of selected element
    int left;
 
    // Right will scan the size of
    // possible subarray in right
    // of selected element
    int right;
 
    // Temp will store size of group
    // associated with every element
    int tmp;
 
    // Loop to find size of subarray
    // for every element of array
    for (int i = 0; i < n; i++) {
        tmp = 1;
        left = i;
 
        // Left will move in left direction
        // and compare difference between
        // itself and element left to it
        while (left - 1 >= 0
               && abs(arr[left] - arr[left - 1])
                      <= K) {
            left--;
            tmp++;
        }
 
        // right will move in right direction
        // and compare difference between
        // itself and element right to it
        right = i;
        while (right + 1 <= n - 1
               && abs(arr[right] - arr[right + 1])
                      <= K) {
            right++;
            tmp++;
        }
 
        // if subarray of much lesser or much
        // greater is found than yet
        // known then update
        if (min > tmp)
            min = tmp;
        if (max < tmp)
            max = tmp;
    }
 
    // Print minimum and maximum
    // possible size of subarray
    cout << min << ", "
         << max << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 5, 6, 7 };
    int K = 2;
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // function call to find maximum
    // and minimum possible sub array
    findMaxMinSubArray(arr, K, n);
 
    return 0;
}


Java




// Java program to find the minimum
// and maximum length subarray such
// that difference between adjacent
// elements is atmost K
import java.io.*;
import java.util.*;
 
class GFG {
     
// Function to find the maximum and
// minimum length subarray
static void findMaxMinSubArray(int arr[],
                               int K, int n)
{
     
    // Initialise minimum and maximum
    // size of subarray in worst case
    int min = n;
    int max = 0;
 
    // Left will scan the size of
    // possible subarray in left
    // of selected element
    int left;
 
    // Right will scan the size of
    // possible subarray in right
    // of selected element
    int right;
 
    // Temp will store size of group
    // associated with every element
    int tmp;
 
    // Loop to find size of subarray
    // for every element of array
    for(int i = 0; i < n; i++)
    {
       tmp = 1;
       left = i;
        
       // Left will move in left direction
       // and compare difference between
       // itself and element left to it
       while (left - 1 >= 0 &&
              Math.abs(arr[left] -
                       arr[left - 1]) <= K)
       {
           left--;
           tmp++;
       }
        
       // Right will move in right direction
       // and compare difference between
       // itself and element right to it
       right = i;
        
       while (right + 1 <= n - 1 &&
              Math.abs(arr[right] -
                       arr[right + 1]) <= K)
       {
           right++;
           tmp++;
       }
        
       // If subarray of much lesser or much
       // greater is found than yet
       // known then update
       if (min > tmp)
           min = tmp;
       if (max < tmp)
           max = tmp;
    }
 
    // Print minimum and maximum
    // possible size of subarray
    System.out.print(min);
    System.out.print(", ");
    System.out.print(max);
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 5, 6, 7 };
    int K = 2;
    int n = arr.length;
     
    // Function call to find maximum
    // and minimum possible sub array
    findMaxMinSubArray(arr, K, n);
}
}
 
// This code is contributed by coder001


Python3




# Python3 program to find the minimum
# and maximum length subarray such
# that difference between adjacent
# elements is atmost K
 
# Function to find the maximum and
# minimum length subarray
def findMaxMinSubArray(arr, K, n):
 
    # Initialise minimum and maximum
    # size of subarray in worst case
    min = n
    max = 0
 
    # Left will scan the size of
    # possible subarray in left
    # of selected element
    left = 0
 
    # Right will scan the size of
    # possible subarray in right
    # of selected element
    right = n
 
    # Temp will store size of group
    # associated with every element
    tmp = 0
 
    # Loop to find size of subarray
    # for every element of array
    for i in range(0, n):
        tmp = 1
        left = i
 
        # Left will move in left direction
        # and compare difference between
        # itself and element left to it
        while (left - 1 >= 0 and
               abs(arr[left] -
                   arr[left - 1]) <= K):
  
            left = left - 1
            tmp = tmp + 1
 
        # Right will move in right direction
        # and compare difference between
        # itself and element right to it
        right = i
        while (right + 1 <= n - 1 and
               abs(arr[right] -
                   arr[right + 1]) <= K):
 
            right = right + 1
            tmp = tmp + 1
 
        # If subarray of much lesser or much
        # greater is found than yet
        # known then update
        if (min > tmp):
            min = tmp
        if (max < tmp):
            max = tmp
 
    # Print minimum and maximum
    # possible size of subarray
    print(min, end = ', ')
    print(max, end = '\n')
 
# Driver Code
arr = [ 1, 2, 5, 6, 7 ]
K = 2
n = len(arr)
 
# Function call to find maximum
# and minimum possible sub array
findMaxMinSubArray(arr, K, n)
 
# This code is contributed by Pratik


C#




// C# program to find the minimum
// and maximum length subarray such
// that difference between adjacent
// elements is atmost K
using System;
class GFG{
     
// Function to find the maximum and
// minimum length subarray
static void findMaxMinSubArray(int[] arr,
                               int K, int n)
{
     
    // Initialise minimum and maximum
    // size of subarray in worst case
    int min = n;
    int max = 0;
 
    // Left will scan the size of
    // possible subarray in left
    // of selected element
    int left;
 
    // Right will scan the size of
    // possible subarray in right
    // of selected element
    int right;
 
    // Temp will store size of group
    // associated with every element
    int tmp;
 
    // Loop to find size of subarray
    // for every element of array
    for(int i = 0; i < n; i++)
    {
       tmp = 1;
       left = i;
        
       // Left will move in left direction
       // and compare difference between
       // itself and element left to it
       while (left - 1 >= 0 &&
              Math.Abs(arr[left] -
                       arr[left - 1]) <= K)
       {
           left--;
           tmp++;
       }
        
       // Right will move in right direction
       // and compare difference between
       // itself and element right to it
       right = i;
       while (right + 1 <= n - 1 &&
              Math.Abs(arr[right] -
                       arr[right + 1]) <= K)
       {
        right++;
        tmp++;
       }
        
       // If subarray of much lesser or much
       // greater is found than yet
       // known then update
       if (min > tmp)
           min = tmp;
       if (max < tmp)
           max = tmp;
    }
     
    // Print minimum and maximum
    // possible size of subarray
    Console.Write(min);
    Console.Write(", ");
    Console.Write(max);
}
 
// Driver code
public static void Main()
{
    int[] arr = { 1, 2, 5, 6, 7 };
    int K = 2;
    int n = arr.Length;
     
    // Function call to find maximum
    // and minimum possible sub array
    findMaxMinSubArray(arr, K, n);
}
}
 
// This code is contributed by AbhiThakur


Javascript




<script>
// Java Script program to find the minimum
// and maximum length subarray such
// that difference between adjacent
// elements is atmost K
     
// Function to find the maximum and
// minimum length subarray
function findMaxMinSubArray(arr, k, n)
{
     
    // Initialise minimum and maximum
    // size of subarray in worst case
    let min = n;
    let max = 0;
 
    // Left will scan the size of
    // possible subarray in left
    // of selected element
    let left;
 
    // Right will scan the size of
    // possible subarray in right
    // of selected element
    let right;
 
    // Temp will store size of group
    // associated with every element
    let tmp;
 
    // Loop to find size of subarray
    // for every element of array
    for(let i = 0; i < n; i++)
    {
    tmp = 1;
    left = i;
         
    // Left will move in left direction
    // and compare difference between
    // itself and element left to it
    while (left - 1 >= 0 &&
            Math.abs(arr[left] -
                    arr[left - 1]) <= K)
    {
        left--;
        tmp++;
    }
         
    // Right will move in right direction
    // and compare difference between
    // itself and element right to it
    right = i;
         
    while (right + 1 <= n - 1 &&
            Math.abs(arr[right] -
                    arr[right + 1]) <= K)
    {
        right++;
        tmp++;
    }
         
    // If subarray of much lesser or much
    // greater is found than yet
    // known then update
    if (min > tmp)
        min = tmp;
    if (max < tmp)
        max = tmp;
    }
 
    // Print minimum and maximum
    // possible size of subarray
    document.write(min);
    document.write(", ");
    document.write(max);
}
 
// Driver code
 
    let arr = [1, 2, 5, 6, 7 ];
    let K = 2;
    let n = arr.length;
     
    // Function call to find maximum
    // and minimum possible sub array
    findMaxMinSubArray(arr, K, n);
 
// This code is contributed by sravan
</script>


Output: 

2, 3

 



Similar Reads

Sum of all numbers formed having 4 atmost X times, 5 atmost Y times and 6 atmost Z times
Given three integers X, Y and Z, the task is to find the sum of all the numbers formed having 4 at most X times, 5 at most Y times, and 6 at most Z times, under mod 10^9+7.Examples: Input: X = 1, Y = 1, Z = 1 Output: 3675 Explanation: 4 + 5 + 6 + 45 + 54 + 56 + 65 + 46 + 64 + 456 + 465 + 546 + 564 + 645 + 654 = 3675 Input: X = 4, Y = 5, Z = 6 Outpu
9 min read
Find Subarray ranges having difference between max and min exactly K
Given an array arr[] of length N and integer K, the task is to print subarray ranges (starting index, ending index) of the array where difference between max and min elements of the subarray is exactly K.( 1-based index ) Examples: Input: arr[] = {2, 1, 3, 4, 2, 6}, K = 2Output: (1, 3), (2, 3), (3, 5), (4, 5)Explanation: In the above array followin
11 min read
Count of subsets having sum of min and max element less than K
Given an integer array arr[] and an integer K, the task is to find the number of non-empty subsets S such that min(S) + max(S) &lt; K.Examples: Input: arr[] = {2, 4, 5, 7} K = 8 Output: 4 Explanation: The possible subsets are {2}, {2, 4}, {2, 4, 5} and {2, 5}Input:: arr[] = {2, 4, 2, 5, 7} K = 10 Output: 26 Approach Sort the input array first.Now u
5 min read
Find min and max values among all maximum leaf nodes from all possible Binary Max Heap
Given a positive integer N, the task is to find the largest and smallest elements, from the maximum leaf nodes of every possible binary max-heap formed by taking the first N natural numbers as the nodes' value of the binary max-heap. Examples: Input: N = 2Output: 1 1Explanation: There is only one maximum binary heap with the nodes {1, 2}: In the ab
7 min read
Longest subarray such that the difference of max and min is at-most one
Given an array of n numbers where the difference between each number and the previous one doesn't exceed one. Find the longest contiguous subarray such that the difference between the maximum and minimum number in the range doesn't exceed one. Examples: Input : {3, 3, 4, 4, 5, 6} Output : 4 The longest subarray here is {3, 3, 4, 4} Input : {7, 7, 7
7 min read
Maximize product of min value of subarray and sum of subarray over all subarrays of length K
Given an array arr[] of N integers, the task is to find the maximum possible value of (min * sum) among all possible subarrays having K elements, where min denotes the smallest integer of the subarray and sum denotes the sum of all elements of the subarray. Example: Input: arr[] = {1, 2, 3, 2}, K = 3Output: 14Explanation: For the subarray {2, 3, 2}
7 min read
Longest subarray having sum of elements atmost K
Given an array arr[] of size N and an integer K, the task is to find the length of the largest subarray having the sum of its elements at most K, where K &gt; 0. Examples: Input: arr[] = {1, 2, 1, 0, 1, 1, 0}, k = 4Output: 5Explanation: {1, 2, 1} =&gt; sum = 4, length = 3 {1, 2, 1, 0}, {2, 1, 0, 1} =&gt; sum = 4, length = 4 {1, 0, 1, 1, 0} =&gt;5 s
12 min read
Count of subsequences with a sum in range [L, R] and difference between max and min element at least X
Given an array arr[] consisting of N positive integers and 3 integers L, R, and X, the task is to find the number of subsequences of size atleast 2 with a sum in the range [L, R], and the difference between the maximum and minimum element is at least X. (N≤15) Examples: Input: arr[] = {1 2 3}, L = 5, R = 6, X = 1Output: 2Explanation: There are two
9 min read
Length of Longest Subarray with same elements in atmost K increments
Given an integer array arr and a number K, the task is to find the length of the longest subarray such that all the elements in this subarray can be made the same in atmost K increments. Examples: Input: arr[] = {2, 0, 4, 6, 7}, K = 6 Output: 3 The longest subarray is {2, 0, 4} which can be made as {4, 4, 4} with total increments = 6 ( ? K ) Input:
18 min read
Find the length of the longest subarray with atmost K occurrences of the integer X
Given two numbers K, X and an array arr[] containing N integers, the task is to find the length of the longest subarray such that it contains atmost 'K' occurrences of integer'X'.Examples: Input: K = 2, X = 2, arr[] = {1, 2, 2, 3, 4} Output: 5 Explanation: The longest sub-array is {1, 2, 2, 3, 4} which is the complete array as it contains at-most '
9 min read
Article Tags :
Practice Tags :