You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
88
+
89
+
The specific steps are as follows:
90
+
91
+
1. Create an array $\textit{preMax}$, where $\textit{preMax}[i]$ represents the maximum value in the interval $[0, i]$ when traversing from left to right.
92
+
2. 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$.
93
+
3. First preprocess the $\textit{preMax}$ array.
94
+
4. 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}$.
95
+
5. Finally return the result array $\textit{ans}$.
96
+
97
+
Time complexity $O(n)$, space complexity $O(n)$. Where $n$ is the length of the array $\textit{nums}$.
86
98
87
99
<!-- tabs:start -->
88
100
89
101
#### Python3
90
102
91
103
```python
92
-
104
+
classSolution:
105
+
defmaxValue(self, nums: List[int]) -> List[int]:
106
+
n =len(nums)
107
+
ans = [0] * n
108
+
pre_max = [nums[0]] * n
109
+
for i inrange(1, n):
110
+
pre_max[i] =max(pre_max[i -1], nums[i])
111
+
suf_min = inf
112
+
for i inrange(n -1, -1, -1):
113
+
ans[i] = ans[i +1] if pre_max[i] > suf_min else pre_max[i]
0 commit comments