Editorial
Sort the seeds by increasing coordinate. Suppose the seed at sorted position was originally seed . Thus, is also the only day on which that seed can be harvested.
Consider only the selected seeds, in coordinate order. Their day indices must strictly decrease and then strictly increase, with at most one turning point.
Let the selected seed harvested earliest be the pivot. For selected seeds to the left of the pivot, the day indices must strictly decrease as coordinates increase. Otherwise, when moving to a farther-left seed that must be harvested earlier, Dadas would cross another selected seed that is still unharvested.
For the same reason, the day indices of selected seeds to the right of the pivot must strictly increase as coordinates increase.
Conversely, every selected set whose day indices strictly decrease and then strictly increase can be harvested. Start at the pivot. In chronological order, each next selected seed lies immediately outside the already harvested range on either the left or the right, so the path never crosses another selected seed that is still unharvested.
Therefore, the problem becomes a maximum-weight valley-shaped bitonic subsequence problem on
where the weight of position is .
Let be the maximum total value of a strictly decreasing subsequence ending at position . Then
Let be the maximum total value of a strictly increasing subsequence starting at position . Then
Both transitions need the maximum DP value among day indices greater than . Since the day indices are exactly the distinct integers from to , a segment tree indexed by day supports the required range maximum queries.
Compute from left to right. Query the maximum on , add , and update position .
Compute from right to left in the same way.
If position is the pivot, the best value is
because the pivot weight was counted twice.
The maximum of this expression over all is the answer. Sorting and segment tree operations give time and memory.
All weights are positive, so the answer is at most the sum of all weights. Hence,
which always fits in a signed 64-bit integer.
Solution written by GPT5.6