Find maximum sum possible equal sum of three stacks

Pattern: Candy and assign cookies

medium

You may only remove items from the tops, which lowers a stack's sum. Start with the three full sums and repeatedly remove the top of the stack with the largest sum; when the three are equal, that is the largest possible common sum (0 if they only meet when empty).

The problem

Three stacks of positive numbers are given as arrays whose first element is the top. Remove zero or more items from the tops so that the three sums are equal, as large as possible, and return that sum (0 if only empty stacks match). The example gives 5.

Think first

  • Can removing from the smallest stack ever help?
  • Which stack must shrink?
  • Why does this find the largest common sum?

Hints

    Brute force, and why it fails

    List every reachable sum of each stack and take the largest in all three: O(n) with sets, also fine.

    The key insight

    Only the tallest stack can be above the answer, so trimming it is always safe, and each item is removed at most once.

    Dry run

    sums8 9 12

    s1 = [3, 2, 1, 1, 1] (sum 8), s2 = [4, 3, 2] (9), s3 = [2, 5, 4, 1] (12). Index 0 is the top.

    Step 1 of 4

    The plan

    a, b, c = the three sums
    while not all equal: remove the top of whichever has the largest sum
    return a
    

    Complexity

    Time
    O(n1 + n2 + n3)
    Space
    O(1)

    Each item is removed at most once.

    Edge cases

    • Already equal: the full sum.
    • No common sum except 0.
    • One-item stacks.
    I've built my logic, show the code

    Java

    class Solution {
        public int maxEqualSum(int[] s1, int[] s2, int[] s3) {
            long a = 0, b = 0, c = 0;
            for (int x : s1) a += x;
            for (int x : s2) b += x;
            for (int x : s3) c += x;
            int i = 0, j = 0, k = 0;                // the next item to remove from each top (index 0 is the top)
            while (!(a == b && b == c)) {
                if (a >= b && a >= c) a -= s1[i++]; // shrink the tallest stack
                else if (b >= a && b >= c) b -= s2[j++];
                else c -= s3[k++];
            }
            return (int) a;                         // all three meet, at 0 if nothing better
        }
    }

    C++

    class Solution {
    public:
        int maxEqualSum(vector<int>& s1, vector<int>& s2, vector<int>& s3) {
            long long a = 0, b = 0, c = 0;
            for (int x : s1) a += x;
            for (int x : s2) b += x;
            for (int x : s3) c += x;
            size_t i = 0, j = 0, k = 0;             // the next item to remove from each top (index 0 is the top)
            while (!(a == b && b == c)) {
                if (a >= b && a >= c) a -= s1[i++]; // shrink the tallest stack
                else if (b >= a && b >= c) b -= s2[j++];
                else c -= s3[k++];
            }
            return static_cast<int>(a);             // all three meet, at 0 if nothing better
        }
    };

    Python

    class Solution:
        def maxEqualSum(self, s1: list[int], s2: list[int], s3: list[int]) -> int:
            a, b, c = sum(s1), sum(s2), sum(s3)
            i = j = k = 0                           # the next item to remove from each top (index 0 is the top)
            while not (a == b == c):
                if a >= b and a >= c:
                    a -= s1[i]                      # shrink the tallest stack
                    i += 1
                elif b >= c:
                    b -= s2[j]
                    j += 1
                else:
                    c -= s3[k]
                    k += 1
            return a                                # all three meet, at 0 if nothing better

    Common mistakes

    • Removing from the bottom (the end of the array).
    • Removing from the smallest stack.

    Similar problems