LeetCode/com/zerroi/leetcode/Three12/MaxArea.java

38 lines
1.1 KiB
Java

package com.zerroi.leetcode.Three12;
/*
* 给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
说明:你不能倾斜容器。
* */
public class MaxArea {
public static void main(String[] args) {
Solution solution = new Solution();
int res = solution.maxArea(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7});
System.out.println("res = " + res);
}
}
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int res = 0;
while (left < right) {
int h = Math.min(height[left], height[right]);
int width = right - left;
res = Math.max(h * width, res);
while (left < right && height[left] <= h) {
left++;
}
while (left < right && height[right] <= h) {
right--;
}
}
return res;
}
}