• + 0 comments

    Java8 with steams

    public static int equalStacks(List<Integer> h1, List<Integer> h2, List<Integer> h3) {
        // Write your code here
            // there are 3 stacks involved
            List<Integer> cumulHeights = new ArrayList<>();
            Integer cumul = 0;
            for (int i = h1.size() - 1; i>=0; i--) {
                cumul += h1.get(i);
                cumulHeights.add(cumul);
            }
            cumul = 0;
            for (int i = h2.size() - 1; i>=0; i--) {
                cumul += h2.get(i);
                cumulHeights.add(cumul);
            }
            cumul = 0;
            for (int i = h3.size() - 1; i>=0; i--) {
                cumul += h3.get(i);
                cumulHeights.add(cumul);
            }
            Optional<Map.Entry<Integer, Long>> mm = cumulHeights.stream().collect(Collectors.groupingBy(s -> s, Collectors.counting())).entrySet()
                    .stream().filter((s) -> s.getValue() == 3).max(Comparator.comparingInt(s -> s.getKey()));
            if (mm.isPresent()) {
                return mm.get().getKey();
            }
            return 0;
        }