Reach End of Array With Max Score Problem
Description
LeetCode Problem 3282.
You are given an integer array nums of length n.
Your goal is to start at index 0 and reach index n - 1. You can only jump to indices greater than your current index.
The score for a jump from index i to index j is calculated as (j - i) * nums[i].
Return the maximum possible total score by the time you reach the last index.
Example 1:
Input: nums = [1,3,1,5]
Output: 7
Explanation:
First, jump to index 1 and then jump to the last index. The final score is 1 * 1 + 2 * 3 = 7.
Example 2:
Input: nums = [4,3,1,3,2]
Output: 16
Explanation:
Jump directly to the last index. The final score is 4 * 4 = 16.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Greedy
A jump from i to j scores (j - i) * nums[i], which is the same as taking j - i unit steps that each earn nums[i]. So every step from index p to p + 1 earns the value of the index we last jumped from. It never hurts to jump from an index with a larger value, so each step should earn the largest nums value seen so far (jumping onward only when a bigger value appears).
Scan the array up to the second-to-last element, keep the running maximum mx, and add it to the answer at every step.
Complexity:
- Time complexity:
O(n) - Space complexity:
O(1)
class Solution:
def findMaximumScore(self, nums: List[int]) -> int:
ans = mx = 0
for x in nums[:-1]:
mx = max(mx, x)
ans += mx
return ans