class RainWater {

	public static long findAccumulatedWater(int[] terrain) {
		if (terrain == null) {
			return 0;
		}
		int maxIndex = 0;
		long totalWater = 0;
		long tempWater = 0;

		for (int index = maxIndex + 1; index < terrain.length; index++) {
			if (terrain[index] >= terrain[maxIndex]) {
				totalWater += tempWater;
				tempWater = 0; // flushing temp water stored
				maxIndex = index;
			} else {
				tempWater += terrain[maxIndex] - terrain[index];
			}
		}

		tempWater = 0;
		int reverseMaxIndex = terrain.length - 1;
		for (int index = reverseMaxIndex - 1; index >= maxIndex; index--) {
			if (terrain[index] >= terrain[reverseMaxIndex]) {
				totalWater += tempWater;
				tempWater = 0; // flushing temp water stored
				reverseMaxIndex = index;
			} else {
				tempWater += terrain[reverseMaxIndex] - terrain[index];
			}
		}

		return totalWater;
	}

}