Maximum count number of valley elements in a subarray of size K | Java implementation to find the maximum number of valley elements in the subarrays of size K ; Function to find the valley elements in the array which contains in the subarrays of the size K ; Increment min_point if element at index i is smaller than element at index i + 1 and i - 1 ; final_point to maintain maximum of min points of subarray ; Iterate over array from kth element ; Leftmost element of subarray ; Rightmost element of subarray ; If new subarray have greater number of min points than previous subarray , then final_point is modified ; Max minimum points in subarray of size k ; Driver Code
class GFG { static void minpoint ( int arr [ ] , int n , int k ) { int min_point = 0 ; for ( int i = 1 ; i < k - 1 ; i ++ ) { if ( arr [ i ] < arr [ i - 1 ] && arr [ i ] < arr [ i + 1 ] ) min_point += 1 ; } int final_point = min_point ; for ( int i = k ; i < n ; i ++ ) { if ( arr [ i - ( k - 1 ) ] < arr [ i - ( k - 1 ) + 1 ] && arr [ i - ( k - 1 ) ] < arr [ i - ( k - 1 ) - 1 ] ) min_point -= 1 ; if ( arr [ i - 1 ] < arr [ i ] && arr [ i - 1 ] < arr [ i - 2 ] ) min_point += 1 ; if ( min_point > final_point ) final_point = min_point ; } System . out . println ( final_point ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 1 , 4 , 2 , 3 , 4 , 1 , 2 } ; int n = arr . length ; int k = 4 ; minpoint ( arr , n , k ) ; } }