Question:
Compute amount of water that can trapped between the blocks using Java

Summary

Let’s assume:

Method: trappingWater

Array: arr


Here, we will implement the two-pointer approach and solve the trapping water problem. 


Solutions

class Solution{

    

    // arr: input array

    // n: size of array

    // Function to find the trapped water between the blocks.

    static long trappingWater(int arr[], int n) { 

        // Your code here

        long cnt = 0;

        long ml = 0, mr = 0;

        int l=0, r=n-1;

        while(l<=r){

            if(arr[l]<arr[r]){

                if(arr[l]<ml){

                    cnt +=ml-arr[l];

                }

                else{

                    ml = arr[l];

                }

                l++;

            }

            else{

                if(arr[r]<mr){

                    cnt += mr-arr[r];

                }

                else{

                    mr = arr[r];

                }

                r--;

            }

        }

        return cnt;

    } 

}


Explanation

  • cnt: The total amount of water that has been trapped is stored in this variable.

  • The variables ml and mr stand for the highest height that can be reached by using the left and right pointers, respectively.

  • The left and right pointers used to navigate the array are denoted by the letters l and r.

  • Until the left pointer (l) is less than or equal to the right pointer (r), this loop continues. 


Answered by:> >user_ua9r6et3w5w

Credit:> >GeekforGeeks


Suggested blogs:

>How to detect whether the linked list has a loop using Java

>How to determine the number of valid groupings for a string using Java

>How to mock a constant value in Python?

>Creating a pivot table by 6 month interval rather than year

>How to Install mariaDB client efficiently inside docker?

>Can I call an API to find out the random seed in Python `hash()` function?

>How remove residual lines after merge two regions using Geopandas in python?


Submit
0 Answers