https://leetcode.com/problems/candy/
給定一個int數(shù)組,每個int代表一個小孩手中的數(shù)字耍攘,給每個小孩分糖果榕栏,保證相鄰的小孩中,手中數(shù)字大的小孩拿到的糖果大于手中數(shù)字小的小孩蕾各,請問最終最少需要多少糖果扒磁。(每個小孩至少有一個糖果)
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
- 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.
解題思路
單獨(dú)一個數(shù)組dp記錄每個小孩的糖果數(shù)量
- 初始化每個小孩的糖果數(shù)量為1
- 正向遍歷,保證鄰居下一個小孩如果數(shù)字大式曲,糖果一定高
- 反向遍歷妨托,保證上一個小孩如果數(shù)字大,糖果一定高
- 反向遍歷的時候有個特例的情況,需要保證i-1的大小不會完全收到i的限制
dp[i - 1] = Math.max(dp[i - 1], dp[i] + 1);
,用這個例子可以看看區(qū)別:input = [1,3,4,5,2]
上代碼
public int candy(int[] ratings) {
int len = ratings.length;
int[] dp = new int[len];
Arrays.fill(dp, 1);
for (int i = 0; i < len - 1; i++) {
if (ratings[i + 1] > ratings[i]) {
dp[i + 1] = dp[i] + 1;
}
}
for (int i = len - 1; i > 0; i--) {
if (ratings[i - 1] > ratings[i]) {
dp[i - 1] = Math.max(dp[i - 1], dp[i] + 1);
// dp[i - 1] = dp[i] + 1; //這個不對检访,input 用[1,3,4,5,2] 可以看出端倪
}
}
int res = 0;
for (int i = 0; i < len; i++) {
res += dp[i];
}
return res;
}