标签:
题目:
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.
思路:
用两个指针分别从数组最左边 left 和最右边 right 同时往中间扫描,可以想到,倘若会出现更大的矩形,那么必定是出现在中间且高度比 left 和 right 中较短的高,所以可以得到如下关键扫描代码:
while (*left <= high && left < right) ++left; while (*right <= high && left < right) --right;
其中, high 是 left 和 right 中较短的值,容积由最短的高度决定,只有两边都比最短的高的情况下,容积才有可能变大。
代码:
1 #define min(a,b) (a) > (b)? (b) : (a) 2 int maxArea(int* height, int heightSize) { 3 int water = 0, *left = height, *right = left + heightSize - 1; 4 int tmp, high; 5 while (left < right) { 6 high = min(*left, *right); 7 tmp = (right - left) * high; 8 if (water < tmp) water = tmp; 9 while (*left <= high && left < right) ++left; 10 while (*right <= high && left < right) --right; 11 } 12 return water; 13 }
标签:
原文地址:http://www.cnblogs.com/YaolongLin/p/4856595.html