




Sponsored
Sponsored
Use these hints if you're stuck. Try solving on your own first.
Does an optimal path have very few patterns? For example, could a path that goes left, turns and goes right, then turns again and goes left be any better than a path that simply goes left, turns, and goes right?
The optimal path turns at most once. That is, the optimal path is one of these: to go left only; to go right only; to go left, turn and go right; or to go right, turn and go left.
Moving x steps left then k-x steps right gives you a range of positions that you can reach.
Use prefix sums to get the sum of all fruits for each possible range.
Use a similar strategy for all the paths that go right, then turn and go left.