Maximum Array Hopping Score I Problem
#3205
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3205.
Given an array nums, you have to get the maximum score starting from index 0 and hopping until you reach the last element of the array.
In each hop, you can jump from index i to an index j > i, and you get a score of (j - i) * nums[j].
Return the maximum score you can get.
Example 1:
Input: nums = [1,5,8]
Output: 16
Explanation:
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:
Input: nums = [4,5,2,8,9,1,3]
Output: 42
Explanation:
We can do the hopping 0 -> 4 -> 6 with a score of (4 - 0) * 9 + (6 - 4) * 3 = 42.
Constraints:
2 <= nums.length <= 10^31 <= nums[i] <= 10^5
Solution
Approach: Memoized Recursion
Define dfs(i) as the best score obtainable starting from index i. From i we can jump to any later index j, earning (j - i) * nums[j] and then continuing from j, so
dfs(i) = max over j > i of (j - i) * nums[j] + dfs(j)
with dfs(n - 1) = 0. The answer is dfs(0). Caching dfs(i) makes each state computed once.
Complexity: O(n2) time and O(n) space.
from functools import lru_cache
class Solution:
def maxScore(self, nums: List[int]) -> int:
@lru_cache(None)
def dfs(i: int) -> int:
return max(
[(j - i) * nums[j] + dfs(j) for j in range(i + 1, len(nums))] or [0]
)
return dfs(0)