问题描述
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?
翻译
有 N 个孩子站成一排。每个孩子都有一个评分值。你要按照以下要求给这些孩子发糖果:
1.每个孩子必须至少有一颗糖果。
2.评分越高的孩子得到的糖果就越多。
你最少要给多少糖果?
思路
从左往右遍历一趟 如果右边>左边 右边糖果=左边+1
从右往左遍历一趟 如果左边>右边 左边糖果=右边+1,同时计算max(右边+1,当前糖果值)
ans[i-1]=max(ans[i-1],ans[i]+1);//从右往左,如果左边大于右边,左边+1
每个人初始糖果为1
代码
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <algorithm>
#include <stdlib.h>
#include <vector>
using namespace std;
//2 1 2 3 2 1 5 4
//2 1 2 3 2 1 2 1
//1 0 1 2 1 0 1 0
const int N = 1e4 + 10;
//核心思想,从左往右一趟右边与左边比较
//从右往左一趟左边与右边比较
int candy(int a[], int n)
{
vector<int>ans(n,1);
for (int i = 0; i < n-1; i++)
{
if (a[i+1] >a[i])
ans[i+1]=ans[i]+1;//从左往右,如果右边大于左边,右边+1
}
int count = ans[n - 1];
for (int i = n - 1; i >= 1; i--)
{
if (a[i-1] > a[i])
ans[i-1]=max(ans[i-1],ans[i]+1);//从右往左,如果左边大于右边,左边+1
count += ans[i-1];
}
return count;
}
int main()
{
int n;
cout << "Please enter the number of children :" << endl;
cin >> n;
cout << "Please enter the rating value of the children :" << endl;
int* a = new int(n);
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
int ans = candy(a, n);
cout << "The number of minimum candies I must give is " << ans << endl;
return 0;
}
测试案例
运行结果
//2 1 2 3 2 1 5 4魅力值
//2 1 2 3 2 1 2 1糖果数量
时间复杂度分析
O(n)
速记
for (int i = 0; i < n-1; i++)
{
if (a[i+1] >a[i])
ans[i+1]=ans[i]+1;//从左往右,如果右边大于左边,右边+1
}
int count = ans[n - 1];
for (int i = n - 1; i >= 1; i--)
{
if (a[i-1] > a[i])
ans[i-1]=max(ans[i-1],ans[i]+1);//从右往左,如果左边大于右边,左边+1
count += ans[i-1];
}