|
| 1 | +package Blind75; |
| 2 | +/* |
| 3 | + * You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). |
| 4 | + Find two lines that together with the x-axis form a container, such that the container contains the most water. |
| 5 | + Return the maximum amount of water a container can store. |
| 6 | + Notice that you may not slant the container. |
| 7 | + */ |
| 8 | +public class Lt11 { |
| 9 | + public static void main(String[] args) { |
| 10 | + int[] height= {1,1}; |
| 11 | + |
| 12 | + System.out.println(maxArea(height)); |
| 13 | + } |
| 14 | + |
| 15 | + public static int maxArea(int[] height) { |
| 16 | + int left = 0; |
| 17 | + int right = height.length - 1; |
| 18 | + int max = 0; |
| 19 | + while(left < right){ |
| 20 | + int w = right - left; //width for every iteration |
| 21 | + int h = Math.min(height[left], height[right]); //height is the min between left and right index |
| 22 | + int area = h * w; //area is height * width |
| 23 | + max = Math.max(max, area); //max between the current max area vs current area of the iteration |
| 24 | + if(height[left] < height[right]) left++; |
| 25 | + else if(height[left] > height[right]) right--; |
| 26 | + else { |
| 27 | + left++; |
| 28 | + right--; |
| 29 | + } |
| 30 | + } |
| 31 | + return max; |
| 32 | + |
| 33 | + } |
| 34 | +} |
0 commit comments