LeetCode OJ - 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?
解题思路:
进行两遍扫描,第一次从前往后扫描,若后面的child的rating比前面高,则多给一个糖果,否则,给他一个糖果。第二遍从后往前扫描,给的糖果数为candy[i] = max(candy[i], candy[i + 1] + 1);
代码如下:
class Solution { public:int candy(vector<int> &ratings) {if (ratings.empty()) return 0;vector<int> candy(ratings.size());candy[0] = 1; //the first children, give he 1 candy//从前往后扫描for (int i = 1; i < ratings.size(); i++) {if (ratings[i] > ratings[i - 1]) {candy[i] = candy[i - 1] + 1;}else {candy[i] = 1;}}//从后向前扫描candy[ratings.size() - 1] = max(candy[ratings.size() - 1], 1);int ans = candy[ratings.size() - 1];for (int i = ratings.size() - 2; i >= 0; i--) {if (ratings[i] > ratings[i + 1]) {candy[i] = max(candy[i], candy[i + 1] + 1);}ans += candy[i];}return ans;} };
转载于:https://www.cnblogs.com/dongguangqing/p/3727164.html
LeetCode OJ - Candy相关推荐
- LeetCode OJ -- Binary Tree Paths
http://blog.ubooksapp.com/ 标签(空格分隔): LeetCode OJ BinaryTree Given a binary tree, return all root-to- ...
- 【重点】LeetCode 135. Candy
LeetCode 135. Candy 博客转载自:http://www.cnblogs.com/grandyang/p/4575026.html 这个题一看就很难...但答案真是清新脱俗啊... S ...
- [LeetCode]135.Candy
[题目] There are N children standing in a line. Each child is assigned a rating value. You are giving ...
- LeetCode之Candy
[题目] There areNchildren standing in a line. Each child is assigned a rating value. You are giving ca ...
- leetcode 135. Candy | 135. 分发糖果(原创图文详解,Java)
题目 https://leetcode.com/problems/candy/ 题解 思路 首先,根据题意,这是一个分糖果问题.本题需要满足两个条件: 每个孩子至少有一个糖果 rating 值较大的孩 ...
- LeetCode OJ:Valid Anagram(有效字谜问题)
Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = & ...
- 【LeetCode OJ 136】Single Number
题目链接:https://leetcode.com/problems/single-number/ 题目:Given an array of integers, every element appea ...
- LeetCode OJ -Happy Number
题目链接:https://leetcode.com/problems/happy-number/ 题目理解:实现isHappy函数,判断一个正整数是否为happy数 happy数:计算要判断的数的每一 ...
- Leetcode OJ: Maximun Subarray
Maximum Subarray Find the contiguous subarray within an array (containing at least one number) which ...
最新文章
- flutter gridview 固定高度_Flutter +携程=?
- opencv学习笔记(六)---图像梯度
- 【Libevent】Ubuntu安装libevent报错问题解决
- PTA 01-复杂度2 Maximum Subsequence Sum (25分)
- Spring EclipseLink NoSQL - 使用MongoDB和Oracle NoSQL DB构建
- java多线程内存模型_Java多线程内存模型
- 一点Python学习资源
- kitserver 6.33 完全简体中文版补丁
- Spring Bean作用域简介
- ## STAMP使用中数据上传注意事项
- 给领导干部讲计算机课的开场,学习计算机课程的心得(1)讲课讲稿.pdf
- 计算机功能转动怎么设定,win7如何使用屏幕旋转功能 电脑使用屏幕旋转功能操作方法...
- word分栏排版时 插入全页宽的表格
- U盘安装Windows 11正式版绕过TPM检查
- 崛起的云平台,彰显信息国产化的中国力量
- 数据结构笔记(王道考研) 第八章:排序
- 华为的用人标准有6条,经典并熟记
- 鬼影没干掉。 病毒已经清除。
- 领跑AIoT场景落地 OFweek智慧家庭高峰论坛圆满落幕!
- 持续交付之三——持续集成