# Find maximum sum possible equal sum of three stacks in C++

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 stacks of positive numbers. We have to find the possible equal maximum sum of stacks with removal of top elements allowed. The stacks are represented as an array. The first index of the array represents the top element of the stack. Suppose the stack elements are like [3, 10], [4, 5] and [2, 1]. The output will be 0. The sum can only be equal after removing all elements from all stacks.

To solve this, we will follow this idea. The idea is to compare the sum of each stack, if they are not equal, then remove the top element of the stack having the maximum sum. We will follow these steps −

• Find sum of all elements of in individual stacks.

• If the sum of all three stacks is equal, then this is the maximum sum.

• Otherwise remove the top element of the stack having the maximum sum among three of stacks. Then repeat step 1 and step 2.

## Example

Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
int maxStackSum(int stk1[], int stk2[], int stk3[], int size1, int size2, int size3) {
int add1 = 0, add2 = 0, add3 = 0;
for (int i=0; i < size1; i++)
for (int i=0; i < size2; i++)
for (int i=0; i < size3; i++)
int top1 =0, top2 = 0, top3 = 0;
int ans = 0;
while (true){
if (top1 == size1 || top2 == size2 || top3 == size3)
return 0;
}
}
int main() {
int stack1[] = { 3, 2, 1, 1, 1 };
int stack2[] = { 4, 3, 2 };
int stack3[] = { 1, 1, 4, 1 };
int size1 = sizeof(stack1)/sizeof(stack1);
int size2 = sizeof(stack2)/sizeof(stack2);
int size3 = sizeof(stack3)/sizeof(stack3);
cout << "The maximum sum is: " << maxStackSum(stack1, stack2, stack3, size1, size2, size3);
}

### Output

The maximum sum is: 5