# C++ code to find maximum stones we can pick from three heaps

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have three numbers a, b and c. There are three heaps of stones with a, b, and c number of stones respectively. Each time we can do these operations −

• Take one stone from the first heap and two stones from the second heap (when the heaps have necessary number of stones)

• Take one stone from the second heap and two stones from the third heap (when the heaps have necessary number of stones)

We have to count maximum how many stones we can collect?

So, if the input is like a = 3; b = 4; c = 5, then the output will be 9, because in two operations we can take two stones from second heap and four stones from third heap, in total we have 6 stones, then take one from first and two from second to get 3 more stones.

## Steps

To solve this, we will follow these steps −

return (minimum of b and floor of (c / 2) + minimum of a and (b - minimum of b and floor of (c / 2)) / 2) * 3

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int a, int b, int c){
return (min(b, c / 2) + min(a, (b - min(b, c / 2)) / 2)) * 3;
}
int main(){
int a = 3;
int b = 4;
int c = 5;
cout << solve(a, b, c) << endl;
}

## Input

3, 4, 5

## Output

9
Updated on 15-Mar-2022 06:36:24