装水面试题

public class Test {

    private static int calculate(int[] testcase) {
        int pLeft = 0;
        int pRight = testcase.length - 1;
        int maxLeft = testcase[pLeft];
        int maxRight = testcase[pRight];

        int volume = 0;
        while (pRight > pLeft) {
            if (maxLeft < maxRight){
                pLeft = pLeft + 1;
                if (testcase[pLeft] >= maxLeft) {
                    maxLeft = testcase[pLeft];
                }
                else{
                    volume = volume + (maxLeft - testcase[pLeft]);
                }
            }else {
                pRight = pRight - 1;
                if (testcase[pRight] >= maxRight) {
                    maxRight = testcase[pRight];
                }
                else {
                    volume = volume + (maxRight - testcase[pRight]);
                }
            }
        }
        System.out.println("total volume:"+volume);
        return volume;
    }

    public static void main(String[] args) {int[] a = {2,5,1,2,3,4,7,7,6};

        calculate(a);

    }
}

原文地址:https://www.cnblogs.com/zhonghan/p/4866796.html