Maximize the profit by selling at | Function to find profit ; Calculating profit for each gadget ; sort the profit array in descending order ; variable to calculate total profit ; check for best M profits ; Driver Code
< ? php function solve ( $ N , $ M , & $ cp , & $ sp ) { $ profit = array_fill ( 0 , $ N , NULL ) ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) $ profit [ $ i ] = $ sp [ $ i ] - $ cp [ $ i ] ; rsort ( $ profit ) ; $ sum = 0 ; for ( $ i = 0 ; $ i < $ M ; $ i ++ ) { if ( $ profit [ $ i ] > 0 ) $ sum += $ profit [ $ i ] ; else break ; } return $ sum ; } $ N = 5 ; $ M = 3 ; $ CP = array ( 5 , 10 , 35 , 7 , 23 ) ; $ SP = array ( 11 , 10 , 0 , 9 , 19 ) ; echo solve ( $ N , $ M , $ CP , $ SP ) ; ? >