Let dp[i][0] be the maximum searched length after choosing directions for people 1 through i, with person i facing left. Let dp[i][1] be the corresponding maximum when person i faces right.
For convenience, set
A0=B0=0,A
The initial values are dp[0][0]=dp[0][1]=0.
Suppose person i faces left. If person i−1 also faces left, the newly covered length is min(Ai−.
If person i−1 faces right, person i−1 may already cover up to Bi−1 units of the gap between the two people. The uncovered part of that gap therefore has length , so person can newly cover
min(Bi,max(0,Ai−
units.
Thus,
dp[i][0]=
If person i faces right, the newly searched interval does not overlap any previously searched interval by a positive length. Therefore,
dp[i][1]=max(dp[i−1][0]
The answer is max(dp[N][0],dp[N][1]). Each transition takes constant time, so the time complexity is O(N).
Solution written by GPT5.6