Bu bir O(nlogn)çözüm. birO(n)Willard Zhan'ın işaret ettiği çözüm bu cevabın sonuna eklenir.
O(nlogn) çözüm
Convience için belirtin f(i,j)=(h[j]−h[i])(j−i).
Tanımlamak l1=1, ve li en küçük endeks olmak li>li−1 ve h[li]<h[li−1]. Benzer şekilde,r1=n, ve ri en büyük endeks olmak ri<ri−1 ve h[ri]>h[ri−1]. Dizilerl1,l2,... ve r1,r2,… hesaplaması kolaydır O(n) saati.
Yok olan dava i<j öyle ki h[i]<h[j] (yani f(i,j)>0) is trivial. We now focus on non-trivial cases. In such cases, to find the solution, we only need to consider such pairs.
For each i<j such that h[i]<h[j], let u be the largest index such that lu≤i, and v be the smallest index such that rv≥j, then h[lu]≤h[i] (otherwise lu+1≤i by definition of lu+1, thus contradicts to the definition of u), and similarly h[rv]≥h[j]. Hence
(h[rv]−h[lu])(rv−lu)≥(h[j]−h[i])(rv−lu)≥(h[j]−h[i])(j−i).
This means we only need to consider pairs
(lu,rv) where
lu<rv.
Denote v(u)=argmaxv: lu<rvf(lu,rv), we have the following lemma.
A pair (lu,rv) where lu<rv, and where there exists u0 such that u<u0 and v<v(u0) or such that u>u0 and v>v(u0), cannot be a final optimum solution.
Proof. According to the definition of v(u0), we have
(h[rv(u0)]−h[lu0])(rv(u0)−lu0)≥(h[rv]−h[lu0])(rv−lu0),
or
(h[rv]−h[rv(u0)])lu0+h[lu0](rv−rv(u0))+h[rv(u0)]rv(u0)−h[rv]rv(u0)≥0.
In the case where u<u0 and v<v(u0), note h[rv]−h[rv(u0)]<0 and rv−rv(u0)>0, and also lu<lu0 and h[lu]>h[lu0], we have
> (h[rv]−h[rv(u0)])lu+h[lu](rv−rv(u0))(h[rv]−h[rv(u0)])lu0+h[lu0](rv−rv(u0)).
This means
(h[rv]−h[rv(u0)])lu+h[lu](rv−rv(u0))+h[rv(u0)]rv(u0)−h[rv]rv(u0)>0,
or
(h[rv(u0)]−h[lu])(rv(u0)−lu)>(h[rv]−h[lu])(rv−lu).
So (lu,rv(u0)) is a strictly better solution than (lu,rv). Proof for the other case is similar. ■
We can compute v(ℓ/2) firstly where ℓ is the length of the sequence l1,l2,…, then recursively compute the optimal solution o1 among (lu,rv)'s for u=1,…,ℓ/2−1 and v=v(ℓ/2),v(ℓ/2)+1,…, and the optimal solution o2 among (lu,rv)'s for u=ℓ/2+1,ℓ/2+2,… and v=1,…,v(ℓ/2). Due to the lemma, the global optimum solution must come from {(lℓ/2,rv(ℓ/2)),o1,o2}.
O(n) Solution
Let f(lu,rv)=−∞ if lu≥rv. The proof of the lemma also shows an important property: for u>u0 and v>v0, if f(lu0,rv0)≥f(lu0,rv), then f(lu,rv0)>f(lu,rv). This means the matrix M[x,y]:=−f(lx,rc−y+1) is a totally monotone matrix where c is the length of the sequence r1,r2,… (so rc−y+1 means the y-th element from the end), then SMAWK algorithm can apply to find the minimum value of M, thus the maximum value of f.