The three stacks s1, s2 and s3, each containing positive integers, are given. The task is to find the maximum possible equal sum that can be achieved by removing elements from the top of the stacks. Elements can be removed from the top of each stack, but the final sum of the remaining elements in all three stacks must be the same. The goal is to determine the maximum possible equal sum that can be achieved after removing elements.
Note: The stacks are represented as arrays, where the first index of the array corresponds to the top element of the stack.
Examples:
Input: s1 = [3, 2, 1, 1, 1], s2 = [4, 3, 2], s3 = [2, 5, 4, 1] Output: 5 Explanation: We can pop 2 elements from the 1st stack, 1 element from the 2nd stack and 2 elements from the 3rd stack.
Greedy Approach - O(n1 + n2 + n3) Time and O(1) Space
The idea is to compare the sum of each stack, if they are not same, remove the top element of the stack having the maximum sum.
Algorithm for solving this problem:
Find the sum of all elements of in individual stacks.
If the sum of all three stacks is the same, then this is the maximum sum.
Else remove the top element of the stack having the maximum sum among three of stacks. Repeat step 1 and step 2.
The approach works because elements are positive. To make sum equal, we must remove some element from stack having more sum, and we can only remove from the top.
Output
5
Suffix Sum and Hash Set - O(n1 + n2 + n3) Time and O(n1 + n2 + n3) Space
The problem can be reinterpreted as we need to find the maximum equal suffix sum of the three array.
As we remove element from the top of stack the remaining sum is the suffix sum up to current element. So, if we put all the suffix sums of stack1 and stack2 in an unordered set and traverse the suffix sum array of stack3, and if we find a suffix sum which is present in all three then it is our ans.
Calculate suffix sum of stack1 and stack2 and insert each element in unorderd_set1 and unordered_set2 respectively.
Calculate suffix sum of stack 3 and store in vector named as suffix.
Traverse the suffix vector from i = 0 to i = prefix.size() - 1
Find an index where the suffix sums of all the three stacks are equal