Container With Most Water

描述

Given n non-negative integers a1,a2,...,ana_1, a_2, …, a_n, where each represents a point at coordinate (i,ai)(i, a_i). n vertical lines are drawn such that the two endpoints of line i is at (i,ai)(i, a_i) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container.

分析

每个容器的面积,取决于最短的木板。

代码

  1. // Container With Most Water
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. public class Solution {
  4. public int maxArea(int[] height) {
  5. int start = 0;
  6. int end = height.length - 1;
  7. int result = Integer.MIN_VALUE;
  8. while (start < end) {
  9. int area = Math.min(height[end], height[start]) * (end - start);
  10. result = Math.max(result, area);
  11. if (height[start] <= height[end]) {
  12. start++;
  13. } else {
  14. end--;
  15. }
  16. }
  17. return result;
  18. }
  19. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/greedy/container-with-most-water.html