2014.2.25 21:34
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?
Solution:
This problem seemed vague to me at first, as the key sentence in the problem: Children with a higher rating get more candies than their neighbors. It didn't specify the case for neighbors with equal rates.
For the sample case {7, 8, 4}, the result will be {1, 2, 1}. While the case {7, 8, 8} yields the result {1, 2, 1}.
Note that problem didn't tell you what to do when neighbors got the same rate value, you might assume that you can choose the way that saves most candies.
My first solution was to cut the sequence in half where neighbors got the same rate. For example {2, 3, 4, 7, 7, 2, 89, 21} => {2, 3, 7} + {7, 2, 89, 21}, and deal with each sequence as a subproblem. But it proved to be a bad idea later, the code wasn't so easy to write.
Then I sought another stupid way: do exactly as the problem told me:
1. Every child get one candy at first.
2. If a child's rate is higher than its left neighbor, he gets one more than his left neighbor.
3. If a child's rate is higher than its right neighbor, he gets one more than his right neighbor.
You would probably have known what I think: initialize an array, scan right, scan left and add'em up.
Total time complexity is O(n). Space complexity is O(n), too.
I believe there are O(n) solutions using only constant space, but haven't come up with a concise solution yet.
Accepted code:
1 // 1AC, DP solution with O(n) time and space. 2 class Solution { 3 public: 4 int candy(vector<int> &ratings) { 5 int i, n; 6 7 n = (int)ratings.size(); 8 if (n == 0) { 9 return 0; 10 } 11 12 vector<int> candy; 13 int result; 14 15 candy.resize(n); 16 for (i = 0; i < n; ++i) { 17 candy[i] = 1; 18 } 19 for (i = 0; i <= n - 2; ++i) { 20 if (ratings[i] < ratings[i + 1]) { 21 // at least one more candy 22 candy[i + 1] = candy[i] + 1; 23 } 24 } 25 for (i = n - 2; i >= 0; --i) { 26 if (ratings[i] > ratings[i + 1] && candy[i] <= candy[i + 1]) { 27 candy[i] = candy[i + 1] + 1; 28 } 29 } 30 result = 0; 31 for (i = 0; i < n; ++i) { 32 result += candy[i]; 33 } 34 candy.clear(); 35 36 return result; 37 } 38 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)