Maximize subarrays count containing the maximum and minimum Array element after deleting at most one element | Java implementation of the above approach ; Returns the count of subarrays which contains both the maximum and minimum elements in the given list ; Initialize the low and high of array ; If current element is less than least element ; If current element is more than highest element ; If current element is equal to low or high then update the pointers ; Update number of subarrays ; Return the result ; Function to find the maximum count of subarrays ; Iterate the array to find the maximum and minimum element ; List after removing the minimum element ; Using assignment operator to copy one vector to other ; List after removing the maximum element ; Driver Code ; Given array ; Function Call
import java . util . * ; import java . lang . * ; class GFG { static long proc ( List < Integer > v ) { int n = v . size ( ) ; int low = v . get ( n - 1 ) , high = v . get ( n - 1 ) ; int p1 = n , p2 = n ; long ans = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { int x = v . get ( i ) ; if ( x < low ) { low = x ; ans = 0 ; } else if ( x > high ) { high = x ; ans = 0 ; } if ( x == low ) p1 = i ; if ( x == high ) p2 = i ; ans += n - Math . max ( p1 , p2 ) ; } return ans ; } static long subarray ( List < Integer > v ) { int n = v . size ( ) ; if ( n <= 1 ) return n ; long ans = proc ( v ) ; int low = v . get ( 0 ) , pos_low = 0 ; int high = v . get ( 0 ) , pos_high = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int x = v . get ( i ) ; if ( x < low ) { low = x ; pos_low = i ; } else if ( x > high ) { high = x ; pos_high = i ; } } List < Integer > u = new ArrayList < > ( Collections . nCopies ( n , 0 ) ) ; Collections . copy ( u , v ) ; u . remove ( pos_low ) ; ans = Math . max ( ans , proc ( u ) ) ; List < Integer > w = new ArrayList < > ( Collections . nCopies ( n , 0 ) ) ; Collections . copy ( w , v ) ; w . remove ( pos_high ) ; return Math . max ( ans , proc ( w ) ) ; } public static void main ( String [ ] args ) { List < Integer > arr = Arrays . asList ( 7 , 2 , 5 , 4 , 3 , 1 ) ; System . out . println ( subarray ( arr ) ) ; } }