荣誉版主
- 积分
- -2403
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2010-5-4
- 最后登录
- 1970-1-1
|
代码应该好理解:
//O(nlog(n)) solution is like quick sort ,
//O(n) solution is like to calculate the smaller closest previous index for each element
int CalcHistogram1(int a[], int n)
{
assert(NULL != a);
if(0 == n) return 0;
assert(n > 0);
//Find the smallest element
int nSmallest = 0;
for (int i = 0; i < n; i++)
{
assert(a[i] >= 0);
nSmallest = a[nSmallest] < a[i] ? nSmallest : i;
}
int nRet = a[nSmallest] * n;
int nLft = CalcHistogram1(a, nSmallest);
int nRgt = CalcHistogram1(a+nSmallest+1, n-nSmallest-1);
nRet = nRet > nLft ? nRet : nLft;
nRet = nRet > nRgt ? nRet : nRgt;
return nRet;
}
int CalcHistogram2(int a[], int n)
{
assert(NULL != a);
assert(n > 0);
int nRet = 0;
stack<int> stk;
stk.push(0);
for (int i = 1; i < n; i++)
{
assert(a[i] >= 0);
if (a[i] >= stk.top())
{
stk.push(a[i]);
continue;
}
while (!stk.empty() && stk.top() > a[i])
{
int nTop = stk.top();
stk.pop();
nRet = nRet > (i-nTop)*a[nTop] ? nRet : (i-nTop)*a[nTop];
}
}
int nEnd = stk.top()+1;
while (!stk.empty())
{
int nTop = stk.top();
stk.pop();
nRet = nRet > (nEnd-nTop)*a[nTop] ? nRet : (nEnd-nTop)*a[nTop];
}
return nRet;
}
|
|