Maximum equal sum of three stacks
Last Updated :
24 Apr, 2025
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 = [2, 3, 4], s3 = [1, 4, 2, 5]
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.
Input: s1 = [3, 10]
s2 = [4, 5]
s3 = [2, 1]
Output: 0
Explanation: Sum can only be equal after removing all elements from all stacks.
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.
C++
#include <iostream>
#include <vector>
using namespace std;
int maxSum(vector<int>& s1, vector<int>& s2, vector<int>& s3) {
int sum1 = 0, sum2 = 0, sum3 = 0;
// Manually summing the elements of s1
for (int i = 0; i < s1.size(); i++) {
sum1 += s1[i];
}
// Manually summing the elements of s2
for (int i = 0; i < s2.size(); i++) {
sum2 += s2[i];
}
// Manually summing the elements of s3
for (int i = 0; i < s3.size(); i++) {
sum3 += s3[i];
}
int top1 = 0, top2 = 0, top3 = 0;
while (true) {
if (top1 == s1.size() || top2 == s2.size() || top3 == s3.size())
return 0;
if (sum1 == sum2 && sum2 == sum3)
return sum1;
if (sum1 >= sum2 && sum1 >= sum3)
sum1 -= s1[top1++];
else if (sum2 >= sum1 && sum2 >= sum3)
sum2 -= s2[top2++];
else
sum3 -= s3[top3++];
}
}
int main() {
vector<int> s1 = {3, 2, 1, 1, 1};
vector<int> s2 = {4, 3, 2};
vector<int> s3 = {1, 1, 4, 1};
cout << maxSum(s1, s2, s3) << endl;
return 0;
}
Java
import java.util.List;
import java.util.ArrayList;
public class GfG {
public static int maxSum(List<Integer> s1, List<Integer> s2, List<Integer> s3) {
int sum1 = 0, sum2 = 0, sum3 = 0;
// Manually summing the elements of s1
for (int i = 0; i < s1.size(); i++) {
sum1 += s1.get(i);
}
// Manually summing the elements of s2
for (int i = 0; i < s2.size(); i++) {
sum2 += s2.get(i);
}
// Manually summing the elements of s3
for (int i = 0; i < s3.size(); i++) {
sum3 += s3.get(i);
}
int top1 = 0, top2 = 0, top3 = 0;
while (true) {
if (top1 == s1.size() || top2 == s2.size() || top3 == s3.size())
return 0;
if (sum1 == sum2 && sum2 == sum3)
return sum1;
if (sum1 >= sum2 && sum1 >= sum3)
sum1 -= s1.get(top1++);
else if (sum2 >= sum1 && sum2 >= sum3)
sum2 -= s2.get(top2++);
else
sum3 -= s3.get(top3++);
}
}
public static void main(String[] args) {
List<Integer> s1 = new ArrayList<>();
s1.add(3);
s1.add(2);
s1.add(1);
s1.add(1);
s1.add(1);
List<Integer> s2 = new ArrayList<>();
s2.add(4);
s2.add(3);
s2.add(2);
List<Integer> s3 = new ArrayList<>();
s3.add(1);
s3.add(1);
s3.add(4);
s3.add(1);
System.out.println(maxSum(s1, s2, s3));
}
}
Python
def max_sum(s1, s2, s3):
sum1 = sum(s1)
sum2 = sum(s2)
sum3 = sum(s3)
top1 = top2 = top3 = 0
while True:
if top1 == len(s1) or top2 == len(s2) or top3 == len(s3):
return 0
if sum1 == sum2 == sum3:
return sum1
if sum1 >= sum2 and sum1 >= sum3:
sum1 -= s1[top1]
top1 += 1
elif sum2 >= sum1 and sum2 >= sum3:
sum2 -= s2[top2]
top2 += 1
else:
sum3 -= s3[top3]
top3 += 1
s1 = [3, 2, 1, 1, 1]
s2 = [4, 3, 2]
s3 = [1, 1, 4, 1]
print(max_sum(s1, s2, s3))
C#
using System;
using System.Collections.Generic;
class GfG {
static int MaxSum(List<int> s1, List<int> s2, List<int> s3) {
int sum1 = 0, sum2 = 0, sum3 = 0;
foreach (var num in s1) sum1 += num;
foreach (var num in s2) sum2 += num;
foreach (var num in s3) sum3 += num;
int top1 = 0, top2 = 0, top3 = 0;
while (true) {
if (top1 == s1.Count || top2 == s2.Count || top3 == s3.Count)
return 0;
if (sum1 == sum2 && sum2 == sum3)
return sum1;
if (sum1 >= sum2 && sum1 >= sum3)
sum1 -= s1[top1++];
else if (sum2 >= sum1 && sum2 >= sum3)
sum2 -= s2[top2++];
else
sum3 -= s3[top3++];
}
}
static void Main() {
List<int> s1 = new List<int> { 3, 2, 1, 1, 1 };
List<int> s2 = new List<int> { 4, 3, 2 };
List<int> s3 = new List<int> { 1, 1, 4, 1 };
Console.WriteLine(MaxSum(s1, s2, s3));
}
}
JavaScript
function maxSum(s1, s2, s3) {
let sum1 = 0, sum2 = 0, sum3 = 0;
for (let i = 0; i < s1.length; i++) {
sum1 += s1[i];
}
for (let i = 0; i < s2.length; i++) {
sum2 += s2[i];
}
for (let i = 0; i < s3.length; i++) {
sum3 += s3[i];
}
let top1 = 0, top2 = 0, top3 = 0;
while (true) {
if (top1 === s1.length || top2 === s2.length || top3 === s3.length)
return 0;
if (sum1 === sum2 && sum2 === sum3)
return sum1;
if (sum1 >= sum2 && sum1 >= sum3)
sum1 -= s1[top1++];
else if (sum2 >= sum1 && sum2 >= sum3)
sum2 -= s2[top2++];
else
sum3 -= s3[top3++];
}
}
const s1 = [3, 2, 1, 1, 1];
const s2 = [4, 3, 2];
const s3 = [1, 1, 4, 1];
console.log(maxSum(s1, s2, s3));
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
- If not found return 0
C++
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int maxSum(vector<int>& s1, vector<int>& s2, vector<int>& s3) {
vector<int> suffix(s3.size() + 1, 0);
int sum1 = 0;
unordered_set<int> st1;
// Calculate suffix sum of s1 and store in unordered_set st1
for (int i = s1.size() - 1; i >= 0; i--) {
sum1 += s1[i];
st1.insert(sum1);
}
int sum2 = 0;
unordered_set<int> st2;
// Calculate suffix sum of s2 and store in unordered_set st2
for (int i = s2.size() - 1; i >= 0; i--) {
sum2 += s2[i];
st2.insert(sum2);
}
// Calculate suffix sum of s3 and store in suffix vector
for (int i = s3.size() - 1; i >= 0; i--) {
suffix[i] = suffix[i + 1] + s3[i];
}
// Find the maximum suffix sum present in all three stacks
for (int i = 0; i < suffix.size(); i++) {
if (st1.find(suffix[i]) != st1.end() && st2.find(suffix[i]) != st2.end()) {
return suffix[i];
}
}
return 0;
}
int main() {
vector<int> s1 = {3, 2, 1, 1, 1};
vector<int> s2 = {4, 3, 2};
vector<int> s3 = {1, 1, 4, 1};
cout << maxSum(s1, s2, s3) << endl;
return 0;
}
Java
import java.util.HashSet;
import java.util.Set;
public class GfG {
public static int maxSum(int[] s1, int[] s2, int[] s3) {
int[] suffix = new int[s3.length + 1];
int sum1 = 0;
Set<Integer> st1 = new HashSet<>();
// Calculate suffix sum of s1 and store in HashSet st1
for (int i = s1.length - 1; i >= 0; i--) {
sum1 += s1[i];
st1.add(sum1);
}
int sum2 = 0;
Set<Integer> st2 = new HashSet<>();
// Calculate suffix sum of s2 and store in HashSet st2
for (int i = s2.length - 1; i >= 0; i--) {
sum2 += s2[i];
st2.add(sum2);
}
// Calculate suffix sum of s3 and store in suffix array
for (int i = s3.length - 1; i >= 0; i--) {
suffix[i] = suffix[i + 1] + s3[i];
}
// Find the maximum suffix sum present in all three stacks
for (int i = 0; i < suffix.length; i++) {
if (st1.contains(suffix[i]) && st2.contains(suffix[i])) {
return suffix[i];
}
}
return 0;
}
public static void main(String[] args) {
int[] s1 = {3, 2, 1, 1, 1};
int[] s2 = {4, 3, 2};
int[] s3 = {1, 1, 4, 1};
System.out.println(maxSum(s1, s2, s3));
}
}
Python
def maxSum(s1, s2, s3):
suffix = [0] * (len(s3) + 1)
sum1 = 0
st1 = set()
# Calculate suffix sum of s1 and store in set st1
for i in range(len(s1) - 1, -1, -1):
sum1 += s1[i]
st1.add(sum1)
sum2 = 0
st2 = set()
# Calculate suffix sum of s2 and store in set st2
for i in range(len(s2) - 1, -1, -1):
sum2 += s2[i]
st2.add(sum2)
# Calculate suffix sum of s3 and store in suffix list
for i in range(len(s3) - 1, -1, -1):
suffix[i] = suffix[i + 1] + s3[i]
# Find the maximum suffix sum present in all three stacks
for i in range(len(suffix)):
if suffix[i] in st1 and suffix[i] in st2:
return suffix[i]
return 0
s1 = [3, 2, 1, 1, 1]
s2 = [4, 3, 2]
s3 = [1, 1, 4, 1]
print(maxSum(s1, s2, s3))
C#
using System;
using System.Collections.Generic;
class Program {
public static int MaxSum(int[] s1, int[] s2, int[] s3) {
int[] suffix = new int[s3.Length + 1];
int sum1 = 0;
HashSet<int> st1 = new HashSet<int>();
// Calculate suffix sum of s1 and store in HashSet st1
for (int i = s1.Length - 1; i >= 0; i--) {
sum1 += s1[i];
st1.Add(sum1);
}
int sum2 = 0;
HashSet<int> st2 = new HashSet<int>();
// Calculate suffix sum of s2 and store in HashSet st2
for (int i = s2.Length - 1; i >= 0; i--) {
sum2 += s2[i];
st2.Add(sum2);
}
// Calculate suffix sum of s3 and store in suffix array
for (int i = s3.Length - 1; i >= 0; i--) {
suffix[i] = suffix[i + 1] + s3[i];
}
// Find the maximum suffix sum present in all three stacks
for (int i = 0; i < suffix.Length; i++) {
if (st1.Contains(suffix[i]) && st2.Contains(suffix[i])) {
return suffix[i];
}
}
return 0;
}
static void Main() {
int[] s1 = {3, 2, 1, 1, 1};
int[] s2 = {4, 3, 2};
int[] s3 = {1, 1, 4, 1};
Console.WriteLine(MaxSum(s1, s2, s3));
}
}
JavaScript
function maxSum(s1, s2, s3) {
const suffix = new Array(s3.length + 1).fill(0);
let sum1 = 0;
const st1 = new Set();
// Calculate suffix sum of s1 and store in Set st1
for (let i = s1.length - 1; i >= 0; i--) {
sum1 += s1[i];
st1.add(sum1);
}
let sum2 = 0;
const st2 = new Set();
// Calculate suffix sum of s2 and store in Set st2
for (let i = s2.length - 1; i >= 0; i--) {
sum2 += s2[i];
st2.add(sum2);
}
// Calculate suffix sum of s3 and store in suffix array
for (let i = s3.length - 1; i >= 0; i--) {
suffix[i] = suffix[i + 1] + s3[i];
}
// Find the maximum suffix sum present in all three stacks
for (let i = 0; i < suffix.length; i++) {
if (st1.has(suffix[i]) && st2.has(suffix[i])) {
return suffix[i];
}
}
return 0;
}
const s1 = [3, 2, 1, 1, 1];
const s2 = [4, 3, 2];
const s3 = [1, 1, 4, 1];
console.log(maxSum(s1, s2, s3));
Maximum equal sum possible in three stacks
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem