DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord account linking.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Largest Rectangle in a Histogram Returns

Back to problem

Editorial

Fix a width www and a target height hhh. It is sufficient to use the www largest elements of BBB for the chosen interval. Sort the interval's AAA values increasingly and those BBB values decreasingly. The interval is feasible exactly when every paired sum is at least hhh.

For every AiA_iAi​, let rir_iri​ be the number of elements BjB_jB satisfying . If the values in a window are sorted as , feasibility is equivalent to for every .

Maintain the frequency of rir_iri​ in a sliding window. Define Dk=#{i:ri≤k}−kD_k=\#\{i:r_i\leq k\}-kDk​=#{i:. All must be non-positive. A segment tree storing the maximum prefix sum of supports insertion, deletion, and checking in .

For every width www, binary-search the largest feasible hhh and maximize whwhwh. The time complexity is O(N2log⁡Nlog⁡V)O(N^2\log N\log V)O(N2logN.

j
​
Ai+Bj≥hA_i+B_j\geq hAi​+Bj​≥h
r(1),⋯ ,r(w)r_{(1)},\cdots,r_{(w)}r(1)​,⋯,r(w)​
r(k)≥kr_{(k)}\geq kr(k)​≥k
kkk
ri​≤
k}−
k
DkD_kDk​
cnt0,cnt1−1,⋯ ,cntw−1\mathrm{cnt}_0,\mathrm{cnt}_1-1,\cdots,\mathrm{cnt}_w-1cnt0​,cnt1​−1,⋯,cntw​−1
O(log⁡N)O(\log N)O(logN)
log
V
)