Input: nums =[1,5,8]Output: 16Explanation:
There are two possible ways to reach the last element:*`0 -> 1 -> 2`with a score of `(1 - 0) * 5 + (2 - 1) * 8 = 13`.*`0 -> 2`with a score of `(2 - 0) * 8 = 16`.
Example 2:
1
2
3
4
5
Input: nums =[4,5,2,8,9,1,3]Output: 42Explanation:
We can do the hopping `0 -> 4 -> 6`with a score of `(4 - 0) * 9 + (6 - 4) * 3
= 42`.
We want the maximum score to reach the last index by hopping from earlier indices. For each index, we can hop to any later index, and the score is (j-i)*nums[j]. We can use dynamic programming from right to left, where dp[i] is the best score starting from i. For each i, try all possible j > i and take the best.
classSolution {
publicintmaxScore(int[] nums) {
int n = nums.length;
int[] dp =newint[n];
for (int i = n-2; i >= 0; --i) {
for (int j = i+1; j < n; ++j) {
dp[i]= Math.max(dp[i], (j-i)*nums[j]+ dp[j]);
}
}
return dp[0];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funmaxScore(nums: IntArray): Int {
val n = nums.size
val dp = IntArray(n)
for (i in n-2 downTo 0) {
for (j in i+1 until n) {
dp[i] = maxOf(dp[i], (j-i)*nums[j] + dp[j])
}
}
return dp[0]
}
}
1
2
3
4
5
6
7
8
classSolution:
defmaxScore(self, nums: list[int]) -> int:
n = len(nums)
dp = [0]*n
for i in range(n-2, -1, -1):
for j in range(i+1, n):
dp[i] = max(dp[i], (j-i)*nums[j] + dp[j])
return dp[0]
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnmax_score(nums: Vec<i32>) -> i32 {
let n = nums.len();
letmut dp =vec![0; n];
for i in (0..n-1).rev() {
for j in i+1..n {
dp[i] = dp[i].max((j asi32- i asi32)*nums[j] + dp[j]);
}
}
dp[0]
}
}