Skip to content

3205. Maximum Array Hopping Score I 👍

Approach 1: DP

  • Time: $O(n^2)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int maxScore(vector<int>& nums) {
    const int n = nums.size();
    // dp[i] := the maximum score to jump from index i to n - 1
    vector<int> dp(n);

    for (int i = n - 1; i >= 0; --i)
      for (int j = i + 1; j < n; ++j)
        // Jump from i to j, and then jump from j to n - 1.
        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
13
14
class Solution {
  public int maxScore(int[] nums) {
    final int n = nums.length;
    // dp[i] := the maximum score to jump from index i to n - 1
    int[] dp = new int[n];

    for (int i = n - 1; i >= 0; --i)
      for (int j = i + 1; j < n; ++j)
        // Jump from i to j, and then jump from j to n - 1.
        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
class Solution:
  def maxScore(self, nums: list[int]) -> int:
    n = len(nums)
    # dp[i] := the maximum score to jump from index i to n - 1
    dp = [0] * n

    for i in reversed(range(n)):
      for j in range(i + 1, n):
        # Jump from i to j, and then jump from j to n - 1.
        dp[i] = max(dp[i], (j - i) * nums[j] + dp[j])

    return dp[0]

Approach 2: Math

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int maxScore(vector<int>& nums) {
    // The optimal jump is the maximum number in the remaining suffix.
    int ans = 0;
    int mx = 0;

    for (int i = nums.size() - 1; i > 0; --i) {
      mx = max(mx, nums[i]);
      ans += mx;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int maxScore(int[] nums) {
    // The optimal jump is the maximum number in the remaining suffix.
    int ans = 0;
    int mx = 0;

    for (int i = nums.length - 1; i > 0; --i) {
      mx = Math.max(mx, nums[i]);
      ans += mx;
    }

    return ans;
  }
}
1
2
3
4
class Solution:
  def maxScore(self, nums: list[int]) -> int:
    # The optimal jump is the maximum number in the remaining suffix.
    return sum(itertools.accumulate(nums[:0:-1], max))