Candy - Leetcode
2015-02-17 08:30
337 查看
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">public class Solution {</span>
public int candy(int[] ratings) { int result=0; int[] helper = new int[ratings.length]; for(int i=1,num=1; i<ratings.length; i++){ if(ratings[i]>ratings[i-1]) helper[i] = num++; else num=1; } for(int i=ratings.length-2,num=1; i>=0; i--) { if(ratings[i]>ratings[i+1]) helper[i] = Math.max(num++, helper[i]); else num=1; } for(int i=0; i<helper.length; i++) result += (helper[i]+1); return result; } }
分析:
遍历的方法:从左到右找出相对于左边的大值,分别递增标志出来; 从右到左找出相对于右边的大值,分别递增标志出来。如果遇到递减的,则不标志。最后累计并实现至少有一个的条件。
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:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
相关文章推荐
- leetcode:Candy
- leetcode135~Candy
- leetcode -- Candy
- LeetCode Candy
- LeetCode(135)Candy
- 【Leetcode】Candy
- [Leetcode 135, Hard] Candy
- 【LeetCode笔记】Candy
- [LeetCode] Candy
- Leetcode_candy
- LeetCode 135 Candy
- [leetcode] Candy Java
- [leetcode][贪心] Candy
- Leetcode Candy
- leetcode-Candy
- [LeetCode] Candy
- LeetCode题解:Candy
- [LeetCode 题解]:Candy
- Candy - LeetCode
- LeetCode - Candy