Maximum sum of increasing order elements from n arrays | PHP program to find maximum sum by selecting a element from n arrays ; To calculate maximum sum by selecting element from each array ; Sort each array ; Store maximum element of last array ; Selecting maximum element from previoulsy selected element ; j = - 1 means no element is found in a [ i ] so return 0 ; Driver Code
< ? php $ M = 4 ; function maximumSum ( $ a , $ n ) { global $ M ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) sort ( $ a [ $ i ] ) ; $ sum = $ a [ $ n - 1 ] [ $ M - 1 ] ; $ prev = $ a [ $ n - 1 ] [ $ M - 1 ] ; $ i ; $ j ; for ( $ i = $ n - 2 ; $ i >= 0 ; $ i -- ) { for ( $ j = $ M - 1 ; $ j >= 0 ; $ j -- ) { if ( $ a [ $ i ] [ $ j ] < $ prev ) { $ prev = $ a [ $ i ] [ $ j ] ; $ sum += $ prev ; break ; } } if ( $ j == -1 ) return 0 ; } return $ sum ; } $ arr = array ( array ( 1 , 7 , 3 , 4 ) , array ( 4 , 2 , 5 , 1 ) , array ( 9 , 5 , 1 , 8 ) ) ; $ n = sizeof ( $ arr ) ; echo maximumSum ( $ arr , $ n ) ; ? >