标签:
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:
What is the minimum candies you must give?
思路:
左到右一遍 右到左一遍
我的代码:
public class Solution { public int candy(int[] ratings) { if(ratings==null || ratings.length==0) return 0; if(ratings.length == 1) return 1; int len = ratings.length; int[] nums = new int[len]; int k = 1; for(int i=1; i<len; i++) { if(ratings[i] < ratings[i+1]) { nums[i] = k; nums[i+1] = k+1; k++; } else { k = 1; nums[i] = Math.max(nums[i], k); nums[i+1] = Math.max(nums[i+1], k); } } k = 1; for(int i=len-1; i>=1; i--) { if(ratings[i-1] > ratings[i]) { nums[i] = Math.max(nums[i], k); nums[i-1] = Math.max(nums[i-1], k+1); k++; } else { k = 1; nums[i-1] = Math.max(nums[i-1], k); nums[i] = Math.max(nums[i], k); } } int rst = 0; for(int num : nums) rst += num; return rst; } }
他人代码:
public class Solution { public int candy(int[] ratings) { if(ratings == null || ratings.length == 0) { return 0; } int[] count = new int[ratings.length]; Arrays.fill(count, 1); int sum = 0; for(int i = 1; i < ratings.length; i++) { if(ratings[i] > ratings[i - 1]) { count[i] = count[i - 1] + 1; } } for(int i = ratings.length - 1; i >= 1; i--) { sum += count[i]; if(ratings[i - 1] > ratings[i] && count[i - 1] <= count[i]) { // second round has two conditions count[i-1] = count[i] + 1; } } sum += count[0]; return sum; } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4513311.html