Algorithms – Part 5: Trapping Rainwater (Brute Force)

In a previous Algorithms series,

Question:

You are given an array of non-negative integers representing the heights of a series of vertical lines on a chart. Find two lines that, together with the x-axis, form a container that can hold the maximum amount of water.

Challenge (as of September 4th, 2023)

I’ve been grappling with this coding problem, and I just can’t seem to find the solution. I’m expecting the answer to be 4, but no matter how I approach it, I’m not getting the result I anticipated.

For the record, this is my current code, and I’ll keep updating it.

import java.io.*;
public class TrappingRainWaterMaximum {
    
    public static int waterCalc(int[] a) {
        int waterLevel = 0;
        int totalAmount = 0;
        int currentWater = 0;
        int maximumAmount = 0;

        for(int i = 0; i < a.length - 1; i++) {
            int max_l = 0;
            int max_r = 0;
            int l = i;
            int r = i;
            int currentHeight = a[i];
            while(r < a.length) {
                if (a[r] > max_r) {
                    max_r = a[r];
                }
                r++;
            }
            while(l >= 0) {
                if (a[l] > max_l) {
                    max_l = a[l];
                }
                l--;
            }
            waterLevel = Math.min(max_r, max_l) - currentHeight;
            if (waterLevel > 0) {
                currentWater = waterLevel;
                maximumAmount = Math.max(maximumAmount, currentWater);
            }
        }
        return maximumAmount;

    }

    public static void main(String[] args) {
        int a[] = {0,1,0,2,1,0,3,1,0,1,2};
        System.out.println(waterCalc(a));
    }


}

Leave a Reply