diff --git a/problems/0135.分发糖果.md b/problems/0135.分发糖果.md index 3456a04c..a805d0d4 100644 --- a/problems/0135.分发糖果.md +++ b/problems/0135.分发糖果.md @@ -324,6 +324,31 @@ function candy(ratings: number[]): number { }; ``` +### Scala + +```scala +object Solution { + def candy(ratings: Array[Int]): Int = { + var candyVec = new Array[Int](ratings.length) + for (i <- candyVec.indices) candyVec(i) = 1 + // 从前向后 + for (i <- 1 until candyVec.length) { + if (ratings(i) > ratings(i - 1)) { + candyVec(i) = candyVec(i - 1) + 1 + } + } + + // 从后向前 + for (i <- (candyVec.length - 2) to 0 by -1) { + if (ratings(i) > ratings(i + 1)) { + candyVec(i) = math.max(candyVec(i), candyVec(i + 1) + 1) + } + } + + candyVec.sum // 求和 + } +} +``` -----------------------