[LeetCode] Jump Game IX

3660. Jump Game IX

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 where j > i is allowed only if nums[j] < nums[i].
  • Jump to index j where j < i is allowed only if nums[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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<int> maxValue(vector<int>& nums) {
int n = nums.size(), ma = -1;
vector<int> res(n, -1), suf(n);
for(int i = n - 1; i >= 0; i--) {
suf[i] = nums[i];
if(i + 1 < n) suf[i] = min(suf[i], suf[i+1]);
}
for(int i = 0; i < n; i++) {
ma = max(ma, nums[i]);
if(i + 1 == n or suf[i+1] >= ma) {
int j = i;
while(j >= 0 and res[j] == -1) res[j--] = ma;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/08/25/PS/LeetCode/jump-game-ix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.