题意:
解题思路:
思路:
1. 从左到右依次遍历,如果[右边元素大于左边元素]ratings[i] > ratings[i-1],则当前评分高于左侧,则将d[i] = d[i - 1] + 1
2. 从右向左遍历,如果左边元素大于右边元素,则取这轮的候选值d[i+1] + 1跟上一轮的d[i]对比,取max即可; => max(d[i], d[i+1] + 1),同时更新max
PHP代码实现:
class Solution {
/**
* @param Integer[] $ratings
* @return Integer
*/
function candy($ratings) {
if (empty($ratings) || count($ratings) == 0) return 0;
$n = count($ratings);
$d = array_fill(0, $n, 0);
$d[0] = 1;
for ($i = 1; $i < $n; $i++) {
if ($ratings[$i] > $ratings[$i - 1]) {
$d[$i] = $d[$i - 1] + 1;
} else {
$d[$i] = 1;
}
}
$sum = $d[$n - 1];
for ($i = $n - 2; $i >= 0; $i--) {
if ($ratings[$i] > $ratings[$i + 1]) {
$d[$i] = max($d[$i], $d[$i + 1] + 1);
}
$sum += $d[$i];
}
return $sum;
}
}
GO代码实现:
func candy(ratings []int) int {
n := len(ratings)
d := make([]int, n)
d[0] = 1
for i := 1; i < n; i++ {
if ratings[i] > ratings[i-1] {
d[i] = d[i-1] + 1
} else {
d[i] = 1
}
}
sum := d[n - 1]
for i := n -2; i >= 0; i-- {
if ratings[i] > ratings[i+1] {
d[i] = max(d[i], d[i+1] + 1)
}
sum += d[i]
}
return sum
}
func max(a, b int) int {
if a > b {
return a
}
return b
}