-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #470 from Kaustubh251002/kaustubh
Added Trapping Rainwater problem to Java_Problems; Added name to contributors.html
- Loading branch information
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
Program's_Contributed_By_Contributors/Java_Programs/Trappingwater.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package gfg_practice; | ||
import java.io.*; | ||
import java.util.*; | ||
import java.lang.*; | ||
class Trappingwater{ | ||
static long trappingWater(int arr[], int n) { | ||
int left[]=new int[n]; | ||
int right[]=new int[n]; | ||
left[0]=0; | ||
right[n-1]=0; | ||
int leftmax=0; | ||
int rightmax=0; | ||
for(int i=1;i<n;i++){ | ||
if(arr[i-1]>leftmax) | ||
leftmax=arr[i-1]; | ||
left[i]=leftmax; | ||
} | ||
for(int i=n-2;i>=0;i--){ | ||
if(arr[i+1]>rightmax) | ||
rightmax=arr[i+1]; | ||
right[i]=rightmax; | ||
} | ||
long amount=0; | ||
for(int i=1;i<n-1;i++){ | ||
int trapped_water= Math.min(left[i],right[i])-arr[i]; | ||
if(trapped_water>0) | ||
amount+=trapped_water; | ||
} | ||
return amount; | ||
} | ||
public static void main(String args[]) throws IOException { | ||
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); | ||
int t=Integer.parseInt(br.readLine().trim());// for inputting the testcases | ||
while(t-->0) { | ||
int n=Integer.parseInt(br.readLine().trim()); | ||
int arr[]=new int[n]; | ||
String inputLine[]=br.readLine().trim().split(" "); | ||
for(int i=0;i<n;i++) { | ||
arr[i]=Integer.parseInt(inputLine[i]); | ||
} | ||
System.out.println(trappingWater(arr,n)); | ||
} | ||
} | ||
} |