Container With Most Water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

两个指针问题。需要计算的是两条线之间的最大面积。使用两个指针,先结算小的那边,因为这边此时的高度成为了下界,不移动这边的话,其他任何情况都会有此下界而且长度变短。

 1 public int maxArea(int[] height) {
 2         if (height == null || height.length < 2) {
 3             return 0;
 4         }
 5         int left = 0;
 6         int right = height.length - 1;
 7         int res = 0;
 8         while (left < right) {
 9             if (height[left] < height[right]) {
10                 res = Math.max(res, height[left] * (right - left));
11                 left++;
12             } else {
13                 res = Math.max(res, height[right] * (right - left));
14                 right--;
15             }
16         }
17         return res;
18     }
View Code

相关文章:

  • 2021-10-28
  • 2021-10-24
  • 2022-01-28
  • 2022-12-23
  • 2022-02-02
  • 2022-01-10
  • 2022-12-23
  • 2021-11-03
猜你喜欢
  • 2021-11-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-23
  • 2021-05-25
  • 2021-07-10
相关资源
相似解决方案