Maximum equal sum of three stacks (original) (raw)

Last Updated : 17 Jan, 2026

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.

Find-maximum-sum-possible-equal-sum-of-three-stacks-2

**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.

Try It Yourselfredirect icon

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:

  1. Find the sum of all elements of in individual stacks.
  2. If the sum of all three stacks is the same, then this is the maximum sum.
  3. 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 #include

using namespace std;

int maxSum(vector& s1, vector& s2, vector& 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 s1 = {3, 2, 1, 1, 1}; vector s2 = {4, 3, 2}; vector 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 s1, List s2, List 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 s1, List s2, List 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.

#include #include #include

using namespace std;

int maxSum(vector& s1, vector& s2, vector& s3) { vector 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 s1 = {3, 2, 1, 1, 1}; vector s2 = {4, 3, 2}; vector 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));

`