代码实现:
方法一:暴力解法——遍历左右边,找出所有面积,取最大值——超时
#define min(a, b) ((a) > (b) ? (b) : (a)) #define max(a, b) ((a) > (b) ? (a) : (b))int maxArea(int *height, int heightSize) {int ans = 0;for (int i = 0; i < heightSize; i++) {for (int j = i; j < heightSize; j++) {int area = min(height[i], height[j]) * (j - i);ans = max(ans, area);}}return ans; }
方法二:双指针
#define min(a, b) ((a) > (b) ? (b) : (a)) #define max(a, b) ((a) > (b) ? (a) : (b))int maxArea(int *height, int heightSize) {int l = 0, r = heightSize - 1;int ans = 0;while (l < r) {int area = min(height[l], height[r]) * (r - l);ans = max(ans, area);if (height[l] <= height[r]) {l++;} else {r--;}}return ans; }