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. // LeetCode, Container With Most Water
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. int maxArea(vector<int> &height) {
  6. int start = 0;
  7. int end = height.size() - 1;
  8. int result = INT_MIN;
  9. while (start < end) {
  10. int area = min(height[end], height[start]) * (end - start);
  11. result = max(result, area);
  12. if (height[start] <= height[end]) {
  13. start++;
  14. } else {
  15. end--;
  16. }
  17. }
  18. return result;
  19. }
  20. };

相关题目

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