Water collected between towers

后端 未结 26 1146
无人共我
无人共我 2020-12-22 16:51

I recently came across an interview question asked by Amazon and I am not able to find an optimized algorithm to solve this question:

You are given an input array wh

26条回答
  •  盖世英雄少女心
    2020-12-22 17:35

    Tested all the Java solution provided, but none of them passes even half of the test-cases I've come up with, so there is one more Java O(n) solution, with all possible cases covered. The algorithm is really simple:

    1) Traverse the input from the beginning, searching for tower that is equal or higher that the given tower, while summing up possible amount of water for lower towers into temporary var.

    2) Once the tower found - add that temporary var into main result var and shorten the input list.

    3) If no more tower found then reverse the remaining input and calculate again.

    public int calculate(List input) {
        int result = doCalculation(input);
        Collections.reverse(input);
        result += doCalculation(input);
        return result;
    }
    
    private static int doCalculation(List input) {
        List copy = new ArrayList<>(input);
        int result = 0;
        for (ListIterator iterator = input.listIterator(); iterator.hasNext(); ) {
            final int firstHill = iterator.next();
            int tempResult = 0;
            int lowerHillsSize = 0;
            while (iterator.hasNext()) {
                final int nextHill = iterator.next();
                if (nextHill >= firstHill) {
                    iterator.previous();
                    result += tempResult;
                    copy = copy.subList(lowerHillsSize + 1, copy.size());
                    break;
                } else {
                    tempResult += firstHill - nextHill;
                    lowerHillsSize++;
                }
            }
        }
        input.clear();
        input.addAll(copy);
        return result;
    }
    

    For the test cases, please, take a look at this test class.

    Feel free to create a pull request if you find uncovered test cases)

提交回复
热议问题