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

C++Server Side ProgrammingProgramming

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++)
      add1 += stk1[i];
   for (int i=0; i < size2; i++)
      add2 += stk2[i];
   for (int i=0; i < size3; i++)
      add3 += stk3[i];
   int top1 =0, top2 = 0, top3 = 0;
   int ans = 0;
   while (true){
      if (top1 == size1 || top2 == size2 || top3 == size3)
         return 0;
      if (add1 == add2 && add2 == add3)
         return add1;
      if (add1 >= add2 && add1 >= add3)
         add1 -= stk1[top1++];
      else if (add2 >= add3 && add2 >= add3)
         add2 -= stk2[top2++];
      else if (add3 >= add2 && add3 >= add1)
         add3 -= stk3[top3++];
   }
}
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[0]);
   int size2 = sizeof(stack2)/sizeof(stack2[0]);
   int size3 = sizeof(stack3)/sizeof(stack3[0]);
   cout << "The maximum sum is: " << maxStackSum(stack1, stack2, stack3, size1, size2, size3);
}

Output

The maximum sum is: 5
raja
Published on 03-Jan-2020 10:40:03
Advertisements