求最大矩形面积,首先,O(n^2)的暴力算法肯定是超时的,不用想了。。必须改进,自己想了想没思路,然后搜了一下,看到求是大肥羊的那篇,思路就是求每个点左右两边比当它高度高的最长下标,类似DP的思想,后面的点可以利用前面求过的结果跳跃前进,非常巧妙,膜拜大牛。。
#include<stdio.h>
int main()
{
int n, a[100000], left[100000], right[100000];
while (scanf("%d", &n), n)
{
int i;
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
left[i] = i;
right[i] = i;
}
int temp;
for (i = 0; i < n; i++)
{
temp = i;
while (temp - 1 >= 0 && a[temp - 1] >= a[i])
temp = left[temp - 1];
left[i] = temp;
}
for (i = n - 1; i >= 0; i--)
{
temp = i;
while (temp + 1 < n && a[temp + 1] >= a[i])
temp = right[temp + 1];
right[i] = temp;
}
long long max = -1, res;
for (i = 0; i < n; i++)
{
res = (long long) a[i] * (long long) (right[i] - left[i] + 1);
if (res > max)
max = res;
}
printf("%lld\n", max);
}
return 0;
}