Maximum Array Hopping Score II Problem
Description
LeetCode Problem 3221.
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^51 <= nums[i] <= 10^5
Solution
Approach: Monotonic Stack
From position i the best move is to jump to the nearest-reaching position holding the largest remaining value: the score of a jump is the distance times the value landed on, so it pays to land on large values and to stay on them for as long as possible.
Build a stack of indices whose values strictly decrease from bottom to top: for each i, pop while the top value is <= nums[i], then push i. These indices are exactly the positions to land on. Then walk through the stack from the bottom with i = 0: for each index j, add (j - i) * nums[j] to the answer and set i = j.
Complexity: time O(n), space O(n).
class Solution:
def maxScore(self, nums: List[int]) -> int:
stk = []
for i, x in enumerate(nums):
while stk and nums[stk[-1]] <= x:
stk.pop()
stk.append(i)
ans = i = 0
for j in stk:
ans += nums[j] * (j - i)
i = j
return ans