HackerRank - candies 【贪心】
HackerRank - candies 【贪心】
Description
Alice is a kindergarten teacher. She wants to give some candies to the children in her class. All the children sit in a line (their positions are fixed), and each of them has a rating score according to his or her performance in the class. Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to save money, so she needs to minimize the total number of candies given to the children.
Input Format
The first line of the input is an integer N, the number of children in Alice’s class. Each of the following N lines contains an integer that indicates the rating of each child.
Constraints
Output Format
Output a single line containing the minimum number of candies Alice must buy.
Sample Input 0
3
1
2
2
Sample Output 0
4
Explanation 0
Here 1, 2, 2 is the rating. Note that when two children have equal rating, they are allowed to have different number of candies. Hence optimal distribution will be 1, 2, 1.
Sample Input 1
10
2
4
2
6
1
7
8
9
2
1
Sample Output 1
19
Explanation 1
Optimal distribution will be 1,2,1,2,1,2,3,4,2,1
题意
有N个小朋友,老师要给小朋友发糖,然后每个小朋友都有一个对应分数,并且他们有一个序列。如果一个小朋友两边坐着的是分数比他低的,那么他的糖数就一定要多于那个人。求老师最少要发的糖数。
思路
先顺序扫一遍,求每个小朋友的左边,连续比他分数高的人有多少个。 EG:6 5 4 2 3 比如这组数据 分数为4的小朋友 他的左边有 6 5 这两个人的分数都比这个小朋友高 所以连续的人数就是2 而 分数为3的那个小朋友 左边是 6 5 4 2 虽然 左边一共有三个人分数比他高,但是离他最近的 并且连续的 分数比他高的 一个都没有。
所以这个小朋友 左边 连续分数比他高的人数就是0 。 然后再逆序扫一遍 求右边。
最后FOR一遍 求max(left, right) + 1 就可以了。 因为 最少是一颗糖
AC代码
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<stack>
#include<numeric>
using namespace std;
const int MAX = 0x3f3f3f3f;
const int MIN = 0xc0c0c0c0;
const int maxn = 1e5 + 5;
typedef long long LL;
struct node
{
int num, left, right;
}q[maxn];
int main()
{
int n;
cin >> n;
int i;
scanf("%d", &q[0].num);
q[0].left = 0;
int temp = 0;
for (i = 1; i < n; i++)
{
scanf("%d", &q[i].num);
if (q[i].num > q[i- 1].num)
temp++;
else temp = 0;
q[i].left = temp;
}
temp = 0;
q[n - 1].right = 0;
for (i = n - 2; i >= 0; i--)
{
if (q[i].num > q[i + 1].num)
temp++;
else
temp = 0;
q[i].right = temp;
}
LL tot = n; //最后结果要用 long long 保存
for (i = 0; i < n; i++)
tot += max(q[i].left, q[i].right);
cout << tot << endl;
}