135. Candy[hard]
2016-09-14 12:17
183 查看
135. 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?
先对ratings进行排序,从小到大发糖果。
发糖果时判断:左右两边的人是否分数比自己小,若是,则糖果数比他们大即可。
细节:两个人分数一样时糖果数不一定一样。
class Solution
{
public:
int n;
int * c;
vector<pair<int,int>> a;
int candy( vector< int >& ratings)
{
n = ratings.size();
c = (int*)calloc(n + 10, sizeof(int));
for(int i = 0 ; i < n ; i++)
a.push_back( make_pair( ratings[ i ] , i ) );
sort( a.begin() , a.end() );
int ans = 0 ;
for(int i = 0; i < n; ++ i)
{
int x = a[i].second;
c[x] = 1;
if (x > 0 && c[x - 1] && ratings[x] > ratings[x - 1])
c[x] = c[x - 1] + 1;
if (x < n - 1 && c[x + 1] && ratings[x] > ratings[x + 1])
c[x] = max(c[x], c[x + 1] + 1);
ans += c[x];
}
return ans;
}
};
相关文章推荐
- Hard-题目34:135. Candy
- 第十一周 leetcode 135. Candy(Hard)
- >>用.NET CF进行HardReset!
- File Uploading to Server Hard Disk using ASP.NET
- Biztalk 2006 editon中新增的实现hardcode Map的属性
- Strange patent filed in China: Method to boot Linux OS from mobile harddisk
- Knowledge and Hard Work
- zoj 1969 Hard to Believe, but True!
- 盘符和/Device/HardDiskVolumeN
- hard disk error mac
- How to Use Disk Utility to Erase a Macintosh Hard Drive
- hardcode 的定义
- Create NTFS Hard Link (创建NTFS硬连接)
- Ubuntu - 硬盘分区、格式化、自动挂载配置 | Hard disk add new partition, format, auto mount in ubuntu
- hdu 1097 A hard puzzle
- Hard way to learn python 笔记3
- Hard way to learn python 笔记9.10
- P/NP/NPC/NP-hard概念的图形解释
- 236. It is hard to please all. 众口难调
- Learn Python The Hard Way学习(11) - 提问