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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxElement ( int a [ ] , int n ) { if ( n < 3 ) return -1 ; int maxElement = a [ 0 ] ; int maxProd = a [ n - 1 ] * a [ 1 ] ; for ( int i = 1 ; i < n ; i ++ ) { int currProd = a [ i - 1 ] * a [ ( i + 1 ) % n ] ; if ( currProd > maxProd ) { maxProd = currProd ; maxElement = a [ i ] ; } else if ( currProd == maxProd ) { maxElement = max ( maxElement , a [ i ] ) ; } } return maxElement ; } int main ( ) { int a [ ] = { 5 , 6 , 4 , 3 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maxElement ( a , n ) ; return 0 ; }