【leetcode】Candy
来源:互联网 发布:java if else switch 编辑:程序博客网 时间:2024/05/16 19:31
原题:http://oj.leetcode.com/problems/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:
- 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?
代码:class Solution {public: int candy(vector<int> &ratings) { // Note: The Solution object is instantiated only once and is reused by each test case. if(ratings.size() == 1){ return 1; } if(ratings.size() < 1){ return 0; } vector<int> result(ratings.size(),1); vector<int> res(ratings.size(),0); while(res != result){ res = result; if(ratings[0]>ratings[1] && result[0]<=result[1]){ result[0] = result[1] + 1; } for(vector<int>::size_type i=1 ; i<result.size()-1 ; i++){ if(ratings[i]>ratings[i-1] && result[i]<=result[i-1]){ result[i] = result[i-1] + 1; } if(ratings[i]>ratings[i+1] && result[i]<=result[i+1]){ result[i] = result[i+1] + 1; } } if(ratings[ratings.size()-1]>ratings[ratings.size()-2] && result[result.size()-1]<=result[result.size()-2]){ result[result.size()-1] = result[result.size()-2] + 1; } } int ret = 0; for(vector<int>::size_type i=0 ; i<result.size() ; i++){ // cout<<result[i] <<"\t"; ret = ret + result[i]; } return ret; }};
总结:先给每人一颗,然后逐次遍历,直到满足要求。
- Leetcode: Candy
- LeetCode:Candy
- [leetcode]Candy
- Leetcode: Candy
- 【leetcode】Candy
- LeetCode:Candy
- [LeetCode] Candy
- [LeetCode]Candy
- [LeetCode] Candy
- 【LeetCode】Candy
- LeetCode | Candy
- Leetcode: Candy
- Candy - LeetCode
- leetcode Candy
- LeetCode Candy
- candy leetcode
- Candy -- LeetCode
- [LeetCode] Candy
- linux下MySQL基础
- C++库研究笔记——程序的本地化
- 半数集问题
- HDU 1527 取石子游戏 威佐夫博奕
- java提高篇(七)-----详解内部类
- 【leetcode】Candy
- String, StringBuffer, StringBuilder拼接字符串的执行效率比较
- 选择性求面积
- JDOM操作XML
- 计算机中整数的表示:原码、反码、补码
- Application、Activity Stack 和 Task的区别
- activitygroup里被管理的所有activity的onactivityresult失效问题
- Vim命令合集
- win8和ubuntu13.10 双系统时间错误