diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 5ce8e900..006285eb 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -9,6 +9,7 @@ 5. [Majority Element](arrays/majority-element.java) 6. [Longest Consecutive Subsequence](arrays/longest-consecutive-subsequence.java) 7. [K-th Element of Two Sorted Arrays](arrays/kth-element-2sorted-array.java) +8. [Trapping Rain Water](arrays/trapping-rain-water.java) ## Graphs diff --git a/algorithms/Java/arrays/trapping-rain-water.java b/algorithms/Java/arrays/trapping-rain-water.java new file mode 100644 index 00000000..1776f020 --- /dev/null +++ b/algorithms/Java/arrays/trapping-rain-water.java @@ -0,0 +1,91 @@ +// Given an array arr[] of N non-negative integers representing the height of blocks. +// If width of each block is 1, compute how much water can be trapped between the blocks during the rainy season. + +//Time Complexity: O(N) +//Auxiliary Space: O(1) + +import java.io.*; +import java.util.*; +import java.lang.*; + + +class Main { + + public static void main (String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases + while(t-->0){ + + //size of array + int n = Integer.parseInt(br.readLine().trim()); + int arr[] = new int[n]; + String inputLine[] = br.readLine().trim().split(" "); + + //adding elements to the array + for(int i=0; i left_max) + // update max in left + left_max = arr[lo]; + else + // water on curr element = max - curr + result += left_max - arr[lo]; + lo++; + } + else { + if (arr[hi] > right_max) + // update right maximum + right_max = arr[hi]; + else + result += right_max - arr[hi]; + hi--; + } + } + + return result; + } +} + +/* Test Case: +Input: +N = 6 +arr[] = {3,0,0,2,0,4} +Output: +10 +Explanation: + ____| +| | +| | | +| | | +300204 + +Total Water Trapped: 3+3+1+3 = 10 + */ +