Jump Game IX Problem
Description
LeetCode Problem 3660.
You are given an integer array nums.
From any index i, you can jump to another index j under the following rules:
- Jump to index
jwherej > iis allowed only ifnums[j] < nums[i]. - Jump to index
jwherej < iis allowed only ifnums[j] > nums[i].
For each index i, find the maximum value in nums that can be reached by following any sequence of valid jumps starting at i.
Return an array ans where ans[i] is the maximum value reachable starting from index i.
Example 1:
Input: nums = [2,1,3]
Output: [2,2,3]
Explanation:
- For i = 0: No jump increases the value.
- For i = 1: Jump to j = 0 as nums[j] = 2 is greater than nums[i].
- For i = 2: Since nums[2] = 3 is the maximum value in nums, no jump increases the value.
Thus, ans = [2, 2, 3].
Example 2:
Input: nums = [2,3,1]
Output: [3,3,3]
Explanation:
- For i = 0: Jump forward to j = 2 as nums[j] = 1 is less than nums[i] = 2, then from i = 2 jump to j = 1 as nums[j] = 3 is greater than nums[2].
- For i = 1: Since nums[1] = 3 is the maximum value in nums, no jump increases the value.
- For i = 2: Jump to j = 1 as nums[j] = 3 is greater than nums[2] = 1.
Thus, ans = [3, 3, 3].
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Prefix Maximum and Suffix Minimum
The last index can always jump back to the maximum of the array, so ans[n - 1] is the prefix maximum up to it.
For any other index i, let preMax[i] be the maximum of nums[0..i] and sufMin the minimum of nums[i + 1..]. If preMax[i] > sufMin, index i can jump back to the position of that prefix maximum, from there jump forward to the position of the suffix minimum, and then reach i + 1. So everything reachable from i + 1 is reachable from i, and ans[i] = ans[i + 1]. Otherwise nothing to the right can be reached and ans[i] = preMax[i].
Build preMax from the left, then scan from the right keeping sufMin.
Complexity: time O(n), space O(n).
from math import inf
class Solution:
def maxValue(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [0] * n
pre_max = [nums[0]] * n
for i in range(1, n):
pre_max[i] = max(pre_max[i - 1], nums[i])
suf_min = inf
for i in range(n - 1, -1, -1):
ans[i] = ans[i + 1] if pre_max[i] > suf_min else pre_max[i]
suf_min = min(suf_min, nums[i])
return ans