Maximum element in an array such that its previous and next element product is maximum | Function to return the largest element such that its previous and next element product is maximum ; Calculate the product of the previous and the next element for the current element ; Update the maximum product ; If current product is equal to the current maximum product then choose the maximum element ; Driver code
function maxElement ( a , n ) { if ( n < 3 ) return - 1 ; let maxElement = a [ 0 ] ; let maxProd = a [ n - 1 ] * a [ 1 ] ; for ( let i = 1 ; i < n ; i ++ ) { let currProd = a [ i - 1 ] * a [ ( i + 1 ) % n ] ; if ( currProd > maxProd ) { maxProd = currProd ; maxElement = a [ i ] ; } else if ( currProd == maxProd ) { maxElement = Math . max ( maxElement , a [ i ] ) ; } } return maxElement ; } let a = [ 5 , 6 , 4 , 3 , 2 ] ; let n = a . length ; document . write ( maxElement ( a , n ) ) ;