Leetcode 动态规划 Candy
2015-09-15 21:11
302 查看
本文senlie原版的,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Total Accepted: 16494 Total
Submissions: 87468My Submissions
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?
题意:n 个小孩,每一个小孩有一个评分。
给小孩发糖。要求:
1)每一个小孩至少一颗糖
2)评分高的小孩发的糖比他旁边两个小孩的多
思路:左右 dp
用一个数组 candy
,表示第 i 个小孩所应该发的最少糖果数
数组 ratings
表示每一个小孩的评分
1.从左到右扫描一遍, candy[i] = 1, if ratings[i] <= ratings[i-1] ; candy[i] = candy[i-1] + 1, if ratings[i] > ratings[i-1]
2.从右到左扫描一遍, candy[i] = candy[i], if ratings[i] <= ratings[i+1] ; candy[i] = max(candy[i], candy[i+1] + 1), if ratings[i] > ratings[i+1]
3.accumulate(candy, candy + n, 0)
复杂度: 时间 O(n), 空间 O(n)
Candy
Total Accepted: 16494 TotalSubmissions: 87468My Submissions
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?
题意:n 个小孩,每一个小孩有一个评分。
给小孩发糖。要求:
1)每一个小孩至少一颗糖
2)评分高的小孩发的糖比他旁边两个小孩的多
思路:左右 dp
用一个数组 candy
,表示第 i 个小孩所应该发的最少糖果数
数组 ratings
表示每一个小孩的评分
1.从左到右扫描一遍, candy[i] = 1, if ratings[i] <= ratings[i-1] ; candy[i] = candy[i-1] + 1, if ratings[i] > ratings[i-1]
2.从右到左扫描一遍, candy[i] = candy[i], if ratings[i] <= ratings[i+1] ; candy[i] = max(candy[i], candy[i+1] + 1), if ratings[i] > ratings[i+1]
3.accumulate(candy, candy + n, 0)
复杂度: 时间 O(n), 空间 O(n)
int candy(vector<int> &ratings){ int n = ratings.size(); vector<int> candy(n, 1); for(int i = 1; i < n; ++i){ candy[i] = ratings[i] <= ratings[i - 1] ? 1 : candy[i - 1] + 1; } for(int i = n - 2; i > -1;--i){ candy[i] = ratings[i] <= ratings[i + 1] ? candy[i] : max(candy[i], candy[i + 1] + 1); } return accumulate(candy.begin(), candy.end(), 0); }
相关文章推荐
- 数据结构应用实例#栈#迷宫寻路
- Pro Git(中文版)
- Java中的类
- 三大集合特点
- LEETCODE-Majority Element
- 【图论】【贪心】[coci CONTEST #1 2014.10.18]MAFIJA
- linux环境配置相关文件
- uva 12167 Proving Equivalences(强连通分量 + 缩点)
- Python 学习(1)---基本知识整理
- windows下TCP服务器和客户端的实现
- CF div2 318 A
- 傅里叶变换在图像处理中的作用
- 如何在github上发布一个带动画介绍的项目
- Git命令参考手册(文本版)
- java__静态导入,可变参数,枚举
- codeforces 244B Undoubtedly Lucky Numbers(set)
- 作业一_随笔2_软件工程的实践项目的自我目标
- Complete Binary Search Tree
- 剑指Offer系列---(21)二叉树的镜像
- 【STL】STL之pair