Problem Description
Explanation:
To solve this problem, we can use dynamic programming to keep track of the maximum score that can be achieved at each index. At each index i
, we calculate the score for jumping from the previous indices to index i
, and update the maximum score at index i
.
- Create an array
dp
of sizen
to store the maximum score at each index. - Initialize
dp[0]
to0
as the maximum score at the starting index. - Iterate over the array from index
1
ton-1
. - For each index
i
, calculate the score for jumping from previous indices to indexi
and updatedp[i]
with the maximum score. - Finally, return
dp[n-1]
which represents the maximum possible total score by reaching the last index.
Solutions
class Solution {
public int maxScore(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
dp[0] = 0;
for (int i = 1; i < n; i++) {
dp[i] = Integer.MIN_VALUE;
for (int j = 0; j < i; j++) {
dp[i] = Math.max(dp[i], dp[j] + (i - j) * nums[j]);
}
}
return dp[n - 1];
}
}
Loading editor...