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