Hackerrank :Candies

Candies

Problem Statement

Alice is a kindergarden 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.

1 <= N <= 105 
1 <= ratingi <= 105

Output Format

Output a single line containing the minimum number of candies Alice must buy.

Sample Input

3  
1  
2  
2

Sample Output

4

Explanation

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.

题意:一堆小孩站成一排,每个小孩有一个分数,现在给各个小孩发糖果,每个小孩最少是一个糖果,如果这个小孩的分数比相邻小孩分数高,那么他得到的糖果也要比相邻小孩糖果多。问一共最少需要多少糖果。

从左到右扫一遍,从右到左扫一遍,求出每一个位置要求的最大值,相加得到结果。

代码:

#pragma warning(disable:4996)
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#include <set>
#include <queue>
#include <stack>
#include <map>
using namespace std;
typedef long long ll;

#define INF 0x7fffffff
const int maxn = 100005;

int n, m;
int rating[maxn];
int dp1[maxn];
int dp2[maxn];

void input()
{
	int i;
	scanf("%d", &n);
	for (i = 1; i <= n; i++)
	{
		scanf("%d", &rating[i]);
		dp1[i] = 1;
		dp2[i] = 1;
	}
}

void solve()
{
	int i;
	for (i = 2; i <= n; i++)
	{
		if (rating[i] > rating[i - 1])
		{
			dp1[i] = dp1[i - 1] + 1;
		}
	}
	for (i = n-1; i >=1 ; i--)
	{
		if (rating[i] > rating[i + 1])
		{
			dp2[i] = dp2[i + 1] + 1;
		}
	}
	ll res = 0;
	for (i = 1; i <= n; i++)
	{
		res += max(dp1[i], dp2[i]);
	}
	cout << res;
}

int main()
{
	//freopen("i.txt","r",stdin);
	//freopen("o.txt","w",stdout);

	input();
	solve();

	//system("pause");
	return 0;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值