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
Copy file name to clipboardExpand all lines: solution/3200-3299/3205.Maximum Array Hopping Score I/README_EN.md
+124
Original file line number
Diff line number
Diff line change
@@ -285,4 +285,128 @@ function maxScore(nums: number[]): number {
285
285
286
286
<!-- solution:end -->
287
287
288
+
<!-- solution:start -->
289
+
290
+
### Solution 3: Monotonic Stack
291
+
292
+
We observe that for the current position $i$, we should jump to the next position $j$ with the maximum value to obtain the maximum score.
293
+
294
+
Therefore, we traverse the array $\text{nums}$, maintaining a stack $\text{stk}$ that is monotonically decreasing from the bottom to the top of the stack. For the current position $i$ being traversed, if the value corresponding to the top element of the stack is less than or equal to $\text{nums}[i]$, we continuously pop the top element of the stack until the stack is empty or the value corresponding to the top element of the stack is greater than $\text{nums}[i]$, and then push $i$ into the stack.
295
+
296
+
Next, we initialize the answer $\text{ans}$ and the current position $i = 0$, traverse the elements in the stack, each time taking out the top element $j$, updating the answer $\text{ans} += \text{nums}[j] \times (j - i)$, and then updating $i = j$.
297
+
298
+
Finally, return the answer $\text{ans}$.
299
+
300
+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array.
301
+
302
+
<!-- tabs:start -->
303
+
304
+
#### Python3
305
+
306
+
```python
307
+
classSolution:
308
+
defmaxScore(self, nums: List[int]) -> int:
309
+
stk = []
310
+
for i, x inenumerate(nums):
311
+
while stk and nums[stk[-1]] <= x:
312
+
stk.pop()
313
+
stk.append(i)
314
+
ans = i =0
315
+
for j in stk:
316
+
ans += nums[j] * (j - i)
317
+
i = j
318
+
return ans
319
+
```
320
+
321
+
#### Java
322
+
323
+
```java
324
+
classSolution {
325
+
publicintmaxScore(int[] nums) {
326
+
Deque<Integer> stk =newArrayDeque<>();
327
+
for (int i =0; i < nums.length; ++i) {
328
+
while (!stk.isEmpty() && nums[stk.peek()] <= nums[i]) {
329
+
stk.pop();
330
+
}
331
+
stk.push(i);
332
+
}
333
+
int ans =0, i =0;
334
+
while (!stk.isEmpty()) {
335
+
int j = stk.pollLast();
336
+
ans += (j - i) * nums[j];
337
+
i = j;
338
+
}
339
+
return ans;
340
+
}
341
+
}
342
+
```
343
+
344
+
#### C++
345
+
346
+
```cpp
347
+
classSolution {
348
+
public:
349
+
int maxScore(vector<int>& nums) {
350
+
vector<int> stk;
351
+
for (int i = 0; i < nums.size(); ++i) {
352
+
while (stk.size() && nums[stk.back()] <= nums[i]) {
0 commit comments