Let be the nearest position left of with height greater than , or if none exists. Dadas wins under exactly these conditions:
Process right endpoints from left to right. A Fenwick tree stores earlier heights; let count those at most . Maintain a stack of indices with decreasing heights. Pop all heights below , recording their number . The remaining top, if any, is .
Combining both types, the contribution of is
Add it to the answer, insert into the Fenwick tree, and push onto the stack. Time complexity is and space complexity is .
Proof
If , Dadas can move to the rightmost internal position higher than . Every remaining internal height is below , so Ttas cannot move. If no such position exists, Dadas cannot move.
If , , and , Dadas can move to and win immediately. If , he has no move. Otherwise, and , so any legal first move reaches some . Ttas replies at the leftmost position after higher than , leaving no legal move for Dadas.
There are candidates with . Such a pair loses precisely when is the first higher position to the right of . These are exactly the indices just popped, so this type contributes wins.
The other type requires . Every height between and is below , so an earlier height in this value range automatically lies left of . If , add . Since has not been inserted, , giving the stated formula.