LeetCode - Candy
7053 단어 LeetCode
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:
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 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.