Intuition
From each starting index, run a DFS following the legal jump rules and record the maximum value reached. Repeat for every starting index. Quadratic, but it directly mirrors the problem statement.
Explanation
Approach
For each i:
- DFS from
iover the implicit graph: edgei → jallowed if (j > iandnums[j] < nums[i]) or (j < iandnums[j] > nums[i]). - Track the maximum value seen during the traversal.
ans[i]= that maximum.
Complexity
- Time:
O(n²)— each DFS may walk the whole array. - Space:
O(n)for the visited set.
Implementation
import java.util.*;
class Solution {
public int[] maxValue(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
for (int start = 0; start < n; start++) {
Set<Integer> seen = new HashSet<>();
seen.add(start);
Deque<Integer> stack = new ArrayDeque<>();
stack.push(start);
int best = nums[start];
while (!stack.isEmpty()) {
int i = stack.pop();
best = Math.max(best, nums[i]);
for (int j = 0; j < n; j++) {
if (seen.contains(j)) continue;
if ((j > i && nums[j] < nums[i]) || (j < i && nums[j] > nums[i])) {
seen.add(j);
stack.push(j);
}
}
}
ans[start] = best;
}
return ans;
}
}