forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_11.java
43 lines (40 loc) · 1.48 KB
/
_11.java
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
package com.fishercoder.solutions;
public class _11 {
public static class Solution1 {
/**
* Time: O(n^2)
* This brute force solution is NOT accepted on LeetCode due to TLE.
*/
public int maxArea(int[] height) {
int maxArea = 0;
for (int left = 0; left < height.length - 1; left++) {
for (int right = height.length - 1; left < right; right--) {
int area = (right - left) * Math.min(height[left], height[right]);
maxArea = Math.max(maxArea, area);
}
}
return maxArea;
}
}
public static class Solution2 {
/**
* Two pointer technique.
* Well explained here: https://leetcode.com/problems/container-with-most-water/discuss/6100/Simple-and-clear-proofexplanation
*/
public int maxArea(int[] height) {
int max = 0;
int left = 0;
int right = height.length - 1;
while (left < right) {
max = Math.max(Math.min(height[left], height[right]) * (right - left), max);
if (height[left] <= height[right]) {
/**if this height is shorter, then we'll need to move it to the right to find a higher one so that it's possible to find a larger area.*/
left++;
} else {
right--;
}
}
return max;
}
}
}