Equal Stacks

  • + 0 comments

    In JAVA8 :

    public static int equalStacks(List<Integer> h1, List<Integer> h2, List<Integer> h3) {
            // Write your code here
            long sum1 = h1.stream().mapToInt(Integer::intValue).sum();
            long sum2 = h2.stream().mapToInt(Integer::intValue).sum();
            long sum3 = h3.stream().mapToInt(Integer::intValue).sum();
            
            Collections.reverse(h1);
            Collections.reverse(h2);
            Collections.reverse(h3);
            
            Stack <Integer> s1 = new Stack<>();
            s1.addAll(h1);
            Stack <Integer> s2 = new Stack<>();
            s2.addAll(h2);
            Stack <Integer> s3 = new Stack<>();
            s3.addAll(h3);
            
            long minHeight;
            while(true){
                if (s1.isEmpty()||s2.isEmpty()||s3.isEmpty()) {
                    return 0;
                }
                
                minHeight = Math.min(sum1, Math.min(sum2, sum3));
                
                while (sum1 > minHeight) {
                    sum1 -= s1.pop();
                }
                while (sum2 > minHeight) {
                    sum2 -= s2.pop();
                }
                while (sum3 > minHeight) {
                    sum3 -= s3.pop();
                }
                
                if (sum1 == sum2 && sum2 == sum3) {
                    return (int)sum1;
                }
            }
        }