Maximize the profit by selling at | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int N , int M , int cp [ ] , int sp [ ] ) { int profit [ N ] ; for ( int i = 0 ; i < N ; i ++ ) profit [ i ] = sp [ i ] - cp [ i ] ; sort ( profit , profit + N , greater < int > ( ) ) ; int sum = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( profit [ i ] > 0 ) sum += profit [ i ] ; else break ; } return sum ; } int main ( ) { int N = 5 , M = 3 ; int CP [ ] = { 5 , 10 , 35 , 7 , 23 } ; int SP [ ] = { 11 , 10 , 0 , 9 , 19 } ; cout << solve ( N , M , CP , SP ) ; return 0 ; }