Problems on Cycles
I have recorded quite a few problems on this blog, but my understanding of some concepts is still not strong enough, so I do not always know how to approach a new problem. This post is about problems involving cycles.
As soon as a cycle appears, it tends to be a headache. Standard dynamic programming no longer applies directly, and many things become difficult to solve.
Pizza With 3n Slices
The task reduces to this: given $n$ values in a cycle, select $n / 3$ non-adjacent values.
There was a similar problem long ago—see here. Use the same treatment: compare the maximum after removing the first element with the maximum after removing the last. The remaining part can then be treated as non-cyclic.
1 | class Solution { |
This can also be solved in $O(n \log n)$ with a deque and a priority queue: repeatedly pop the maximum value, then undo its effect. I think this approach is excellent.