Maximum triplet sum in array | This function assumes that there are at least three elements in arr [ ] . ; Initialize Maximum , second maximum and third maximum element ; Update Maximum , second maximum and third maximum element ; Update second maximum and third maximum element ; Update third maximum element ; Driven code
< ? php function maxTripletSum ( $ arr , $ n ) { $ maxA = PHP_INT_MIN ; $ maxB = PHP_INT_MIN ; $ maxC = PHP_INT_MIN ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] > $ maxA ) { $ maxC = $ maxB ; $ maxB = $ maxA ; $ maxA = $ arr [ $ i ] ; } else if ( $ arr [ $ i ] > $ maxB ) { $ maxC = $ maxB ; $ maxB = $ arr [ $ i ] ; } else if ( $ arr [ $ i ] > $ maxC ) $ maxC = $ arr [ $ i ] ; } return ( $ maxA + $ maxB + $ maxC ) ; } $ arr = array ( 1 , 0 , 8 , 6 , 4 , 2 ) ; $ n = count ( $ arr ) ; echo maxTripletSum ( $ arr , $ n ) ; ? >