You are given two boxes. The first box is empty while in the second, there are 3 piles of coins. Whenever you choose a pile of X coins (x>=1) from the second box, the coins in the first box increases by X but only one gold coin gets reduced from the pile present in the second box. You can choose only one pile at a time. You can repeat this operation K times. Every pile contains coins between 1 and 50 only, initially. Find the maximum number of coins that can be extracted in K given operations.
Examples :
Input : stacks{ 9, 1, 4} and K = 10
Output : 51
Input : stacks{ 4, 5, 5} and K = 4
Output : 18
#include <bits/stdc++.h>
using namespace std ;
// Driver Code
int main() {
// Declaring the number of coins in each stack
int arr[3]={ 4 , 5 , 5} ;
// 'n' is the 'K' operations that can be performed and 'ans' will contain the result
int n = 4, ans=0;
// sorting the 'arr'
sort( arr , arr + 3 ) ;
//looping for every operation
for(int i = 1 ; i <= n ; i++ ) {
//condition to check whether the stack with maximum coins is empty or not
if( arr[2] ) {
//'ans' becomes 'ans' plus coins in largest stack
ans += arr[2] ;
// Decreasing one coin from chosen stack in the second box
arr[2]-- ;
}
sort( arr , arr + 3 ) ; //sorting after every operation
}
// Maximum coins that can be taken
cout << ans << endl ;
return 0 ;
}
let the stacks be{4 ,5 ,5} and ‘K’ = 4
- First chosen stack = 5 => ans = 5 and stack = {4 , 4 , 5}
- Second chosen stack = 5 => ans = 10 and stack = {4 , 4 , 4}
- First chosen stack = 4 => ans = 14 and stack = {4 , 4 , 3}
- First chosen stack = 4 => ans = 18 and stack = {3 , 4 , 3}
Hence, the maximum possible number of coins is 18.