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,AN+1=L,BN+1=0.
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−Ai−1,Bi).
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 max(0,Ai−Ai−1−Bi−1), so person i can newly cover
min(Bi,max(0,Ai−Ai−1−Bi−1))
units.
Thus,
dp[i][0]=max(dp[i−1][0]+min(Ai−Ai−1,Bi),dp[i−1][1]+min(Bi,max(0,Ai−Ai−1−Bi−1))).
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],dp[i−1][1])+min(Ai+1−Ai,Bi).
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