-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMostwater.java
More file actions
55 lines (50 loc) · 1.51 KB
/
Mostwater.java
File metadata and controls
55 lines (50 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.ArrayList;
public class Mostwater {
// public static int mostWater(ArrayList <Integer> arr){
// int max = Integer.MIN_VALUE;
// //brute force
// for(int i = 0; i<arr.size()-1; i++){
// for(int j = i+1 ;j <arr.size(); j++){
// int width = j-i;
// int height = Math.min(arr.get(i), arr.get(j));
// if(max < width * height){
// max = width * height;
// }
// }
// }
// return max;
// }
//optimized
public static int storeWater(ArrayList <Integer> list){
int maxWater = Integer.MIN_VALUE;
int lp = 0;
int rp = list.size()-1;
while(lp < rp){
int ht = Math.min(list.get(lp), list.get(rp));
int wd = rp - lp;
int currWater = ht * wd;
maxWater = Math.max(maxWater, currWater);
if(list.get(lp) < list.get(rp)){
lp++;
}else{
rp--;
}
}
return maxWater;
}
public static void main(String args[]){
int arr[] = {1,8,6,2,5,4,8,3,7};
// System.out.println(mostWater(arr));
ArrayList <Integer> height = new ArrayList<>();
height.add(1);
height.add(8);
height.add(6);
height.add(2);
height.add(5);
height.add(4);
height.add(8);
height.add(3);
height.add(7);
System.out.println(storeWater(height));
}
}