F - Starry Landscape Photo Editorial by spheniscine


Consider fixing the highest number that would be in the set, call it \(x\). Then consider its position in \(B\), as well as the positions of all values \(< x\).

Let \(L_x\) be the number of values \(<x\) that are to the left of \(x\). By choosing \(l\) appropriately you can include anywhere from \(0\) to \(L_x\) elements that are closest to \(x\). Similarly for values \(<x\) that are to the right of \(x\), therefore the number of valid subsets with maximum value \(x\) is \(f(x) = (L_x + 1) (R_x + 1)\).

The number of values \(<x\) in a range can be updated and queried quickly using some kind of point-add-range-sum data structure; options include segment tree and Fenwick tree. Overall, the solution should take \(O(N \log N)\) time.

posted:
last update: