Maximize subarrays count containing the maximum and minimum Array element after deleting at most one element | Returns the count of subarrays which contains both the maximum and minimum elements in the given vector ; 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 ; Vector after removing the minimum element ; Using assignment operator to copy one vector to other ; Vector after removing the maximum element ; Given array ; Function Call
function proc ( v ) { let n = v . length ; let low = v [ n - 1 ] , high = v [ n - 1 ] ; let p1 = n , p2 = n ; let ans = 0 ; for ( let i = n - 1 ; i >= 0 ; i -- ) { let x = v [ 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 ; } function subarray ( v ) { let n = v . length ; if ( n <= 1 ) { return n ; } let ans = proc ( v ) ; let low = v [ 0 ] , pos_low = 0 , high = v [ 0 ] , pos_high = 0 ; for ( let i = 1 ; i < n ; i ++ ) { let x = v [ i ] ; if ( x < low ) { low = x ; pos_low = i ; } else if ( x > high ) { high = x ; pos_high = i ; } } let u = [ ... v ] ; u . splice ( pos_low , 1 ) ; ans = Math . max ( ans , proc ( u ) ) ; let w = [ ... v ] ; w . splice ( pos_high , 1 ) ; return Math . max ( ans , proc ( w ) ) ; } let v = [ ] ; v . push ( 7 ) ; v . push ( 2 ) ; v . push ( 5 ) ; v . push ( 4 ) ; v . push ( 3 ) ; v . push ( 1 ) ; document . write ( subarray ( v ) ) ;