Maximize the profit by selling at | Java implementation of above approach : ; 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
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static int solve ( int N , int M , int cp [ ] , int sp [ ] ) { Integer [ ] profit = new Integer [ N ] ; for ( int i = 0 ; i < N ; i ++ ) profit [ i ] = sp [ i ] - cp [ i ] ; Arrays . sort ( profit , Collections . reverseOrder ( ) ) ; int sum = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( profit [ i ] > 0 ) sum += profit [ i ] ; else break ; } return sum ; } public static void main ( String args [ ] ) { int N = 5 , M = 3 ; int CP [ ] = { 5 , 10 , 35 , 7 , 23 } ; int SP [ ] = { 11 , 10 , 0 , 9 , 19 } ; System . out . println ( solve ( N , M , CP , SP ) ) ; } }