Equal Stacks

  • + 0 comments

    Java O(n1 + n2 + n3)

    public static int equalStacks(List<Integer> h1, List<Integer> h2, List<Integer> h3) {
            Stack<Integer> stack1 = new Stack<>();
            Stack<Integer> stack2 = new Stack<>();
            Stack<Integer> stack3 = new Stack<>();
    
            int sum1 = 0, sum2 = 0, sum3 = 0;
    
            for (int i = h1.size() - 1; i >= 0; i--) {
                stack1.push(h1.get(i));
                sum1 += h1.get(i);
            }
    
            for (int i = h2.size() - 1; i >= 0; i--) {
                stack2.push(h2.get(i));
                sum2 += h2.get(i);
            }
    
            for (int i = h3.size() - 1; i >= 0; i--) {
                stack3.push(h3.get(i));
                sum3 += h3.get(i);
            }
    
            while (!stack1.isEmpty() && !stack2.isEmpty() && !stack3.isEmpty()) {
                int minSum = Math.min(sum1, Math.min(sum2, sum3));
    
                while (sum1 > minSum) sum1 -= stack1.pop();
                while (sum2 > minSum) sum2 -= stack2.pop();
                while (sum3 > minSum) sum3 -= stack3.pop();
    
                if (sum1 == sum2 && sum2 == sum3) return sum1;
            }
    
            return 0; 
        }