分发糖果
解题思路:贪心算法、两次遍历
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; } }
原文地址:https://www.cnblogs.com/erdanyang/p/11128372.html
时间: 2024-10-12 05:22:12