3660. Jump Game IX
Description
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
j
wherej > i
is allowed only ifnums[j] < nums[i]
. - Jump to index
j
wherej < i
is 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 toj = 0
asnums[j] = 2
is greater thannums[i]
. - For
i = 2
: Sincenums[2] = 3
is the maximum value innums
, 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 toj = 2
asnums[j] = 1
is less thannums[i] = 2
, then fromi = 2
jump toj = 1
asnums[j] = 3
is greater thannums[2]
. - For
i = 1
: Sincenums[1] = 3
is the maximum value innums
, no jump increases the value. - For
i = 2
: Jump toj = 1
asnums[j] = 3
is greater thannums[2] = 1
.
Thus, ans = [3, 3, 3]
.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
Solutions
Solution 1: Dynamic Programming
If \(i = n - 1\), then it can jump to the maximum value in \(\textit{nums}\), so \(\textit{ans}[i] = \max(\textit{nums})\). For other positions \(i\), we can calculate by maintaining a prefix maximum array and a suffix minimum variable.
The specific steps are as follows:
- Create an array \(\textit{preMax}\), where \(\textit{preMax}[i]\) represents the maximum value in the interval \([0, i]\) when traversing from left to right.
- Create a variable \(\textit{sufMin}\), which represents the minimum value to the right of the current element when traversing from right to left. Initially \(\textit{sufMin} = \infty\).
- First preprocess the \(\textit{preMax}\) array.
- Next, traverse the array from right to left. For each position \(i\), if \(\textit{preMax}[i] > \textit{sufMin}\), it means we can jump from \(i\) to the position where \(\textit{preMax}\) is located, then jump to the position where \(\textit{sufMin}\) is located, and finally jump to \(i + 1\). Therefore, the numbers that can be reached from \(i + 1\) can also be reached from \(i\), so \(\textit{ans}[i] = \textit{ans}[i + 1]\); otherwise update to \(\textit{preMax}[i]\). Then update \(\textit{sufMin}\).
- Finally return the result array \(\textit{ans}\).
Time complexity \(O(n)\), space complexity \(O(n)\). Where \(n\) is the length of the array \(\textit{nums}\).
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|