Equal Stacks

  • + 0 comments

    Java 8 - Based on all way subtracting a cylinder from the highest stack. This naturally protects from indexing exceptions and negative values since 0,0,0 is always true.

        public static int equalStacks(List<Integer> h1, List<Integer> h2, List<Integer> h3) {
            int s1h = h1.stream().collect(Collectors.summingInt(Integer::intValue));
            int s2h = h2.stream().collect(Collectors.summingInt(Integer::intValue));
            int s3h = h3.stream().collect(Collectors.summingInt(Integer::intValue));
            
            int s1i=0,s2i=0,s3i=0;
            
            while(s1h != s2h || s1h != s3h) {
                if (s1h>=s2h && s1h>=s3h )
                    s1h -= h1.get(s1i++);
                else if (s2h>=s1h && s2h>=s3h )
                    s2h -= h2.get(s2i++);
                else if (s3h>=s1h && s3h>=s2h )
                    s3h -= h3.get(s3i++);
            }
            return s1h;
        }