【LeetCode】135. Candy 分發糖果(Hard)(JAVA)每日一題
阿新 • • 發佈:2021-01-04
技術標籤:LeetCode 每日一題java演算法leetcode資料結構面試
【LeetCode】135. Candy 分發糖果(Hard)(JAVA)
題目地址: https://leetcode.com/problems/candy/
題目描述:
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Example 1:
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
題目大意
老師想給孩子們分發糖果,有 N個孩子站成了一條直線,老師會根據每個孩子的表現,預先給他們評分。
你需要按照以下要求,幫助老師給這些孩子分發糖果:
- 每個孩子至少分配到 1 個糖果。
- 相鄰的孩子中,評分高的孩子必須獲得更多的糖果。
那麼這樣下來,老師至少需要準備多少顆糖果呢?
解題方法
- 遍歷兩次,一次從左到右,一次從右到左,結果儲存到一個一維數組裡
- 先從左到右,如果當前元素大於前面的元素,前一個的結果 + 1,min[i] = min[i - 1] + 1
- 然後從右到左,如果當前元素大於前面的元素,前一個的結果 + 1, min[i + 1] + 1,然後和從左到右遍歷的結果比較,取大的值
class Solution { public int candy(int[] ratings) { if (ratings.length <= 0) return 0; int[] dp = new int[ratings.length]; dp[0] = 1; for (int i = 1; i < dp.length; i++) { if (ratings[i] > ratings[i - 1]) { dp[i] = dp[i - 1] + 1; } else { dp[i] = 1; } } int res = dp[dp.length - 1]; for (int i = dp.length - 2; i >= 0; i--) { if (ratings[i] > ratings[i + 1]) { dp[i] = Math.max(dp[i + 1] + 1, dp[i]); } res += dp[i]; } return res; } }
執行耗時:3 ms,擊敗了66.08% 的Java使用者
記憶體消耗:39.5 MB,擊敗了66.45% 的Java使用者