leetcode 17 Candy
来源:互联网 发布:算法导论第三版 15.4-4 编辑:程序博客网 时间:2024/05/13 18:58
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,从前往后扫描,如果第i个小孩等级比第i-1个高,那么i的糖数目等于i-1的糖数目+1;
从后往前扫描,如果第i个的小孩的等级比i+1个小孩高,但是糖的数目却小或者相等,那么i的糖数目等于i+1的糖数目+1。
该算法时间复杂度为O(N)
#include<iostream>#include<cstdio>#include<vector>using namespace std;int candy(vector<int> &ratings){ vector<int> count(ratings.size(),1); int i,len=count.size(); for(i=0;i<len;i++) { if(ratings[i+1]>ratings[i]&&count[i+1]<=count[i]) count[i+1]=count[i]+1; } for(i=len-1;i>=0;i--) { if(ratings[i-1]>ratings[i]&&count[i-1]<=count[i]) count[i-1]=count[i]+1; } int sum=0; for(i=0;i<len;i++) sum+=count[i]; return sum;}int main(int argc,char *argv[]){ freopen("input.txt","r",stdin); vector<int> v; int num,tmp; cin>>num; while(num--) { cin>>tmp; v.push_back(tmp); } cout<<candy(v)<<endl; return 0;}
这个题只要知道了模拟的方法,就比较简单了。
0 0
- leetcode 17 Candy
- LeetCode 17 Candy
- 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
- hdu 1195 Open the Lock 暴力穷举
- warning:performSelector may cause a leak because its selector is unknown
- java编码问题
- ecshop产品列表页按订单表销量排序
- 西洋歌剧的起源与历史
- leetcode 17 Candy
- log4j不生成日志文件问题
- 暑期web 开发1
- C++ 动态库链接
- 2014.07.10 性能优化:系统首页展示数据过多,反映太慢
- 在cocos2d里面如何使用Texture Packer和像素格式来优化spritesheet
- Apidemos-->Views-Lists-Cursor(people)学习
- 线程编程六:ThreadLocal,静态但不要共享的实现
- Android 开源框架Universal-Image-Loader完全解析(一)--- 基本介绍及使用