-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathContainerWithMostWater.java
More file actions
33 lines (31 loc) · 1.18 KB
/
ContainerWithMostWater.java
File metadata and controls
33 lines (31 loc) · 1.18 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
package com.company;
public class ContainerWithMostWater {
/**
* Initially
* we consider the area constituting the exterior most lines.
* Now, to maximize the area, we need to consider the area
* between the lines of larger lengths.
* If we try to move the pointer at the longer line inwards,
* we won't gain any increase in area,
* since it is limited by the shorter line.
* But moving the shorter line's pointer
* could turn out to be beneficial,
* as per the same argument,
* despite the reduction in the width.
* This is done since a relatively longer line obtained
* by moving the shorter line's pointer
* might overcome the reduction in area caused by the width reduction.
*/
public int maxArea(int[] height) {
int maxarea = 0;
int left = 0;
int right = height.length - 1;
while (left < right) {
int tmparea = Math.min(height[left], height[right]) * (right - left);
maxarea = Math.max(maxarea, tmparea);
if (height[left] < height[right]) left++;
else right--;
}
return maxarea;
}
}