【LeetCode】11. Container With Most Water

xiaoxiao2021-02-28  153

11. Container With Most Water

介绍

Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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 and n is at least 2.

题意:在二维坐标系中,(i, ai) 表示从 (i, 0) 到 (i, ai) 的一条线段,任意两条这样的线段和 x 轴组成一个木桶,找出能够盛水最多的木桶,返回其容积。

解答

对于木桶的容量计算,如果下标i和j(i

class Solution { public: int maxArea(vector<int>& height) { int i = 0, j = height.size()-1; int area = INT_MIN; while(i < j) { if(height[i] < height[j]) { area = max(area,(j-i)*height[i]); ++i; } else { area = max(area,(j-i)*height[j]); --j; } } return area; } };
转载请注明原文地址: https://www.6miu.com/read-22079.html

最新回复(0)