问题描述:
In stock market, HH-index (historically highest) of the current price is k means that current price is the highest price in the previous k days, but not the highest one in the previous k + 1 days. For example, the price changes as showed in the following figure.
The price in Day 5 is the highest in Days 5,4,3,2, but not highest one in Days 5,4,3,2,1, thus HH(5) = 4; The price in Day 4 is the highest in Days 4,3,2, but not highest one in Days 4,3,2,1, thus HH(4) = 3; The price in Day 3 is the highest in Day 3, but not highest one in Days 3,2, thus HH(3) = 1; The input in this example is 8,4,3,5,6,2, the answer is 1,1,1,3,4,1. Given the prices of n days, please give an algorithm of O(n) time complexity to calculate the HH−index of all days.
解题思路:该题目是典型的HH问题的;我们使用动态规划来解这道题目;
如果其前面的i-1的高度等于i时,则很明显H[i]=H[i-1];如果前面的i-1的高度小于i的高度时,我们不仅得到H[i]包含H[i-1]并且一直追溯到前面最近的高度相同的price[j];如果price[i-1]>price[i],则很明显H[i]z只有其自身;
pseudo-code
for i=1...n
{
HH[i]=1;//初始化为其自身
if(price[i]==price[i-1])
HH[i]=HH[i-1]+1;
else if(price[i]>price[i-1])
{
j=i-1;
while(j>0&&price[i]>price[j])
{
HH[i]=HH[i]+HH[j];
j=j-HH[j];
}
}
}