public int trap(int[] A) {

        if (A.length < 2) {
            return 0;
        }

        int block = 0;
        int head = 0;
        int left = head;

        int tail = A.length - 1;
        int right = tail - 1;

        //move from head to tail, if A[head] <= A[head + 1], there is no block before head, start from new head index
        while (head < A.length - 1 && A[head] <= A[head + 1]) {
            head++;
        }
        left = head + 1;

        //move from tail to head, if A[tail] <= A[tail - 1], there is no block after tail, start from new tail index
        while (tail > 0 && A[tail] <= A[tail - 1]) {
            tail--;
        }
        right = tail - 1;

        //add up the blocks from head
        int sumLeft = 0;
        while (left < A.length) {
            if (A[left] < A[head]) {
                //record the value inside the area
                sumLeft += A[left];
                left++;
            } else {
                //calculate the blocks -- the total area minus the empty value.
                block = block + (left - head - 1) * Math.min(A[left], A[head]) - sumLeft;
                //move the head to this position, move to calculate the next part
                head = left;
                left++;
                sumLeft = 0;
            }
        }

        //add up the blocks in the rest part from tail
        int sumRight = 0;
        while (head < tail) {
            if (A[right] < A[tail]) {
                //record the value of the rest area
                sumRight += A[right];
                right--;
            } else {
                //calculate the blocks --  the total area minus the empty recorded value
                block = block + (tail - right - 1) * Math.min(A[tail], A[right]) - sumRight;
                //move tail to current position, move and calculate the rest part
                tail = right;
                right--;
                sumRight = 0;
            }
        }

        //check both from head to tail && tail to head, include all the parts
        return block;

    }