标签:++ == -- return ati 贪心 amp 分发 int
分发糖果
解题思路:贪心算法、两次遍历
class Solution { public int candy(int[] ratings) { int len = ratings.length; if(len==0){ return 0; } int[] cands = new int[len]; for(int i=0;i<len;i++){ cands[i] = 1; } for(int i=0;i<len-1;i++){ if(ratings[i+1]>ratings[i]&&cands[i+1]<=cands[i]){ cands[i+1]=cands[i]+1; } } for(int i=len-1;i>0;i--){ if(ratings[i-1]>ratings[i]&&cands[i-1]<=cands[i]){ cands[i-1]=cands[i]+1; } } int sum = 0; for(int i=0;i<len;i++){ sum += cands[i]; } return sum; } }
标签:++ == -- return ati 贪心 amp 分发 int
原文地址:https://www.cnblogs.com/erdanyang/p/11128372.html