Problem
You are given an integer array nums
of length n
.
Your goal is to start at index 0
and reach index n - 1
. You can only jump to indices greater than your current index.
The score for a jump from index i
to index j
is calculated as (j - i) * nums[i]
.
Return the maximum possible total score by the time you reach the last index.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^5
Solution
Intuition
At each index, you can jump to any index to the right. The score for a jump from i to j is (j - i) * nums[i]. We want to maximize the total score to reach the last index. This is a classic DP problem: for each position, the best way to reach it is from some previous position, and we want to maximize the sum.
Approach
Let dp[i] be the maximum score to reach index i. For each i, we can jump to any j > i, so for each j, dp[j] = max(dp[j], dp[i] + (j - i) * nums[i]). However, this is O(n^2) and too slow.
But, since (j - i) * nums[i] is linear in j, and we want to maximize dp[j], we can use a monotonic queue or convex hull trick to optimize. However, for this problem, a greedy approach works: the best jump is either directly to the end or to the next highest value. For each index, try all possible jumps (in practice, the optimal is to jump directly to the end or to the next local maximum).
But since the constraints are large, we can process from the end backwards: for each i, dp[i] = max over all j > i of (j - i) * nums[i] + dp[j]. Since we can jump to any j > i, the optimal is to jump directly to the end: dp[i] = (n-1 - i) * nums[i]. But sometimes, an intermediate jump gives a better result. So, we process from the end, and for each i, dp[i] = max((j - i) * nums[i] + dp[j]) for all j > i. This is a classic convex hull trick/monotonic queue optimization, but for simplicity, we can use a segment tree or keep track of the best so far.
For this solution, we provide a simple O(n^2) DP for clarity, but in practice, for large n, convex hull trick or segment tree is needed.
Code
C++
|
|
Go
|
|
Java
|
|
Kotlin
|
|
Python
|
|
Rust
|
|
TypeScript
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
— For each index, we check all possible jumps to the right. - 🧺 Space complexity:
O(n)
— For the DP array.