题目:
盛最多水的容器
关键词:
双指针
思路:依次遍历i到n-1个值为左边高度,找到[i+1, n]中最大的值作为右边高度,求面积。窗口往右边滑动时,高度大于当前高度才更新左边的下标,否则无意义。
#include <stdio.h>
#define MIN(x, y) ((x) < (y) ? (x) : (y))
#define MAX(x, y) ((x) > (y) ? (x) : (y))
static int lookUpMaxOfArray(const int *array, int size, int offset)
{
int i, j;
int max = 0;
for (i = offset, j = offset; i < size; i++) {
if (array[i] > max) {
max = array[i];
j = i;
}
}
return j;
}
static int findFirstLarger(const int *array, int size, int offset, int val)
{
int i;
for (i = offset; i < size; i++) {
if (array[i] > val) {
printf("%s, array[%d]=%d\n", __func__, i, array[i]);
return i;
}
}
return 0;
}
int maxArea(int* height, int heightSize)
{
if ((height == NULL) || (heightSize < 2)) {
printf("invalid args input\n");
return 0;
}
int i, j;
int curMatrix;
int matirxMax = 0;
for (i = 0; i <heightSize - 1;) {
for (j = i + 1; j < heightSize; j++) {
j = lookUpMaxOfArray(height, heightSize, j);
curMatrix = MIN(height[i], height[j])*(j - i);
matirxMax = MAX(curMatrix, matirxMax);
// printf("[%s_%d]j=%d, rightMaxY=%d, i=%d, curMatrix=%d\n", __func__, __LINE__, j, height[j], i, curMatrix);
}
i = findFirstLarger(height, heightSize, i + 1, height[i]);
if (i == 0) {
// printf("array[%d]=%d===========================\n", i, height[i]);
break;
} else {
// printf("[%s_%d], i=%d, leftMaxY=%d, matirxMax=%d---------\n", __func__, __LINE__, i, height[i], matirxMax);
}
}
return matirxMax;
}
网友评论