Trapping Rain Water

find the amount of water that can be trapped within a given set of bars in linear time and constant space.

package org.wesome.dsalgo;

public class TrappingRainWater {
    public static int trap(int[] barArray) {
        // maintain two pointers leftSideBar and rightSideBar, pointing to the leftmost and rightmost index of the input array
        int leftSideBar = 0, rightSideBar = barArray.length - 1, water = 0;
        int maxBarFromLeft = barArray[leftSideBar];
        int maxBarFromRight = barArray[rightSideBar];
        while (leftSideBar < rightSideBar) {
            if (barArray[leftSideBar] <= barArray[rightSideBar]) {
                leftSideBar++;
                maxBarFromLeft = Integer.max(maxBarFromLeft, barArray[leftSideBar]);
                water = water + (maxBarFromLeft - barArray[leftSideBar]);
            } else {
                rightSideBar--;
                maxBarFromRight = Integer.max(maxBarFromRight, barArray[rightSideBar]);
                water = water + (maxBarFromRight - barArray[rightSideBar]);
            }
        }
        return water;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class TrappingRainWaterTest {
    @Test
    void trappingRainWaterTest1() {
        int[] heights = new int[]{3, 2, 1, 3};
        Assertions.assertEquals(6, TrappingRainWater.trap(heights));
    }

    @Test
    void trappingRainWaterTest2() {
        int[] heights = new int[]{0, 1, 0, 2, 1, 0, 3, 2, 1, 2, 1};
        Assertions.assertEquals(6, TrappingRainWater.trap(heights));
    }
}
plugins {
    id 'java'
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on