Trapping Rainwater Java Code

Trapping Rainwater 

Trapping Rainwater Java Programming Code:


import java.util.*;

public class TrappingRainWater {
    public static int TrappingRain(int height[]) {
        int n = height.length;
        // claculate left max boundary - array
        int leftMax[] = new int[n];
        leftMax[0] = height[0];
        for (int i = 1; i < n; i++) {
            leftMax[i] = Math.max(height[i], leftMax[i - 1]);
        }
        // claculate right max boundary - array
        int rightMax[] = new int[n];
        rightMax[n - 1] = height[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            rightMax[i] = Math.max(height[i], rightMax[i + 1]);
        }
        int trappedWater = 0;
        // loop
        for (int i = 0; i < n; i++) {
            // waterLevel = min(leftmax bound, right bound)
            int waterLevel = Math.min(leftMax[i], rightMax[i]);
            // trapped water = waterLevel - hight[i]
            trappedWater += waterLevel - height[i];
        }
        return trappedWater;

    }

    public static void main(String[] args) {
        int height[] = { 1, 4, 2, 0, 6, 3, 2, 5 };
        System.out.println(TrappingRain(height));
    }
}

 

No comments:

Post a Comment

Max Sub Array Sum: Kadane's Algorithm

Code of: Max Sub Array Sum: Kadane's Algorithm. public class MaxSubArraySumKadanesALgorithm {     public static void Kadane ( int ...