mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
@ -177,21 +177,20 @@ class Solution {
|
|||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def candy(self, ratings: List[int]) -> int:
|
def candy(self, ratings: List[int]) -> int:
|
||||||
candyVec = [1] * len(ratings)
|
n = len(ratings)
|
||||||
|
candies = [1] * n
|
||||||
|
|
||||||
# 从前向后遍历,处理右侧比左侧评分高的情况
|
# Forward pass: handle cases where right rating is higher than left
|
||||||
for i in range(1, len(ratings)):
|
for i in range(1, n):
|
||||||
if ratings[i] > ratings[i - 1]:
|
if ratings[i] > ratings[i - 1]:
|
||||||
candyVec[i] = candyVec[i - 1] + 1
|
candies[i] = candies[i - 1] + 1
|
||||||
|
|
||||||
# 从后向前遍历,处理左侧比右侧评分高的情况
|
# Backward pass: handle cases where left rating is higher than right
|
||||||
for i in range(len(ratings) - 2, -1, -1):
|
for i in range(n - 2, -1, -1):
|
||||||
if ratings[i] > ratings[i + 1]:
|
if ratings[i] > ratings[i + 1]:
|
||||||
candyVec[i] = max(candyVec[i], candyVec[i + 1] + 1)
|
candies[i] = max(candies[i], candies[i + 1] + 1)
|
||||||
|
|
||||||
# 统计结果
|
return sum(candies)
|
||||||
result = sum(candyVec)
|
|
||||||
return result
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user