103-Candy
2016-06-03 23:40
501 查看
–135. Candy My Submissions QuestionEditorial Solution
Total Accepted: 52699 Total Submissions: 232597 Difficulty: Hard
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?
题意: 给一队小孩一串数,现在发糖果,要求发糖果最少
满足 当前点邻域有序
面试碰到这个题:
1.特殊情况,递增或递减 直接就可以算出
2.非特殊呢?
当时思考时是先确定最小点的值,然后划分,后面发现子问题不满足同样特性,进一步思考,如何划分其实可以得到一种解,
就是 如果碰到两个值相等,中间就可以切开,问题是不一定有相同值
如果没相同值呢?那么有最小点集合,以最小点为切分对象。。转化为1,2
但不是最好的思路
最好的思路:
找到规律~
你想下只有顺序递增的时候,给糖果也是依次递增的
反过来呢,逆序递增的时候,给糖果也是逆序递增的
那么如何求出呢?
这样可以顺序扫描一遍,得出递增序列的糖果值
同样逆序扫描一遍,得出逆序递增的糖果值,当然递增的时候是取较大值的
整个过程不是很好理解,需要多举特例是想想过程
Total Accepted: 52699 Total Submissions: 232597 Difficulty: Hard
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?
题意: 给一队小孩一串数,现在发糖果,要求发糖果最少
满足 当前点邻域有序
面试碰到这个题:
1.特殊情况,递增或递减 直接就可以算出
2.非特殊呢?
当时思考时是先确定最小点的值,然后划分,后面发现子问题不满足同样特性,进一步思考,如何划分其实可以得到一种解,
就是 如果碰到两个值相等,中间就可以切开,问题是不一定有相同值
如果没相同值呢?那么有最小点集合,以最小点为切分对象。。转化为1,2
但不是最好的思路
最好的思路:
找到规律~
你想下只有顺序递增的时候,给糖果也是依次递增的
反过来呢,逆序递增的时候,给糖果也是逆序递增的
那么如何求出呢?
这样可以顺序扫描一遍,得出递增序列的糖果值
同样逆序扫描一遍,得出逆序递增的糖果值,当然递增的时候是取较大值的
整个过程不是很好理解,需要多举特例是想想过程
class Solution { public: int candy(vector<int>& ratings) { int n=ratings.size(); vector<int> increment(n,1); int asc_len=1; for(int i=1;i<n;++i){//顺序递增的时候 if(ratings[i]>ratings[i-1]) increment[i]=max(++asc_len,increment[i]); else asc_len=1; } for(int j=n-1,asc_len=1;j>0;--j){//逆序递增的时候 if(ratings[j-1]>ratings[j]) increment[j-1]=max(++asc_len,increment[j-1]); else asc_len=1; } return accumulate(increment.begin(),increment.end(),0); } }; //test case0: //input: 2 3 2 //output: 1 2 1 // 1 2 1 // 1 2 1 //test case1: //input: 1 2 3 4 3 2 // 1 2 3 4 1 1 // 1 1 1 3 2 1 // 1 2 3 4 2 1=13 //testcase3: //input:1 2 //output:1 2=3
相关文章推荐
- Candy
- LeetCode:Candy
- 开此博客的目的
- LeetCode-Candy
- 聊天室Candy-chat 部署(Candy— a JavaScript-based multi-user chat client)
- 【LeetCode-135】Candy
- [LeetCode]135. Candy
- Leetcode: Candy
- HDU 4465 Candy 概率 (2012成都区域赛B题)
- Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
- [LeetCode] Candy
- hdu4465 Candy
- poj 3372 Candy Distribution
- Candy算子 分割 车辆
- 免费领Candy币
- 手把手教你领candy.one糖果
- [leetcode]: 575. Distribute Candies
- 171. Excel Sheet Column Number\172. Factorial Trailing Zeroes\134. Gas Station\135. Candy
- FCPX主题插件:玻璃质感图文展示动画包装 CANDY GLASS for Mac版 v1.0最新破解版
- 算法第十三周作业01