Problem Description
Given an array nums, you start at index 0 and want to reach the last element by making one or more “hops”. In each hop, you can jump from index i to an index j (with j > i) and earn a score equal to (j - i) * nums[j]. Your task is to compute the maximum score you can achieve when reaching the final element.
Key Insights
- The problem is similar to jump game problems but with a score function weighted by both distance and the value at the destination.
- A direct Dynamic Programming formulation leads to a recurrence: dp[j] = max{ dp[i] + (j - i) * nums[j] } for all i < j.
- Rewriting the recurrence as dp[j] = j * nums[j] + max{ dp[i] - i * nums[j] } for i < j shows that for each j we need to query a function based on prior indices.
- By viewing each candidate i as a “line” with slope = -i and intercept = dp[i], the query becomes a typical line query (Convex Hull Trick) where you want to maximize (line.slope * nums[j] + line.intercept).
- Using a data structure that supports adding lines and querying for maximum values (for example, a LiChao tree) provides an efficient O(n log n) solution.
Space and Time Complexity
Time Complexity: O(n log n)
Space Complexity: O(n)
Solution
We solve this problem by maintaining an array dp where dp[j] represents the maximum score when reaching index j. We observe that the recurrence: dp[j] = j * nums[j] + max{ dp[i] - i * nums[j] } for all previous indices (i < j) can be interpreted as querying a set of lines, where each line corresponds to a previous index i and is defined by: line(x) = (-i) * x + dp[i] The query for each index j is made with x = nums[j], and then we update dp[j] accordingly by adding j * nums[j]. As we process the array from left to right, we add a new line for each index that can be used for future queries.
The algorithm uses a LiChao Tree (or a similar convex hull optimization data structure) that supports:
- Inserting a line in O(log n)
- Querying the maximum value among the stored lines in O(log n)
This approach ensures the overall time complexity is O(n log n) while using O(n) space for both the dp array and the LiChao tree.