From cfb10d2e2a24324a319fec0986dee0ef465394fc Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 1 Jun 2023 01:35:04 -0500 Subject: [PATCH] =?UTF-8?q?Update=200135.=E5=88=86=E5=8F=91=E7=B3=96?= =?UTF-8?q?=E6=9E=9C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0135.分发糖果.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/problems/0135.分发糖果.md b/problems/0135.分发糖果.md index 1ba1563f..cf3ccc8e 100644 --- a/problems/0135.分发糖果.md +++ b/problems/0135.分发糖果.md @@ -178,13 +178,21 @@ class Solution { class Solution: def candy(self, ratings: List[int]) -> int: candyVec = [1] * len(ratings) + + # 从前向后遍历,处理右侧比左侧评分高的情况 for i in range(1, len(ratings)): if ratings[i] > ratings[i - 1]: candyVec[i] = candyVec[i - 1] + 1 - for j in range(len(ratings) - 2, -1, -1): - if ratings[j] > ratings[j + 1]: - candyVec[j] = max(candyVec[j], candyVec[j + 1] + 1) - return sum(candyVec) + + # 从后向前遍历,处理左侧比右侧评分高的情况 + for i in range(len(ratings) - 2, -1, -1): + if ratings[i] > ratings[i + 1]: + candyVec[i] = max(candyVec[i], candyVec[i + 1] + 1) + + # 统计结果 + result = sum(candyVec) + return result + ``` ### Go