Question Name:Minimum number

#include <cstdio>
#include <string>
using namespace std;

typedef long long ll;

int a[100005],b[100005];

inline int maxi(int x,int y) {
	return (x>y)?x:y;
}

int main() {
int i,j,n;
ll ans;

	scanf("%d",&n);
	for (i=1;i<=n;++i) {
		scanf("%d",&a[i]);
	}
	a[0]=a[1];
	a[n+1]=a[n];
	for (i=1;i<=n;++i) {
		if ((a[i]<=a[i+1]) && (a[i]<=a[i-1])) {
			b[i]=1;
			for (j=i-1;j && (a[j]>a[j+1]);--j) {
				b[j]=b[j+1]+1;
			}
			for (;i<n && (a[i+1]>a[i]);++i) {
				b[i+1]=b[i]+1;
			}
		}
	}
	ans=0;
	for (i=1;i<=n;++i) {
		if ((a[i]>a[i-1]) && (a[i]>a[i+1])) {
			b[i]=maxi(b[i-1],b[i+1])+1;
		}
		ans+=b[i];
	}
	printf("%Ld\n",ans);
	return 0;

}
  • Problem Description
    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.

    Constraints
    1<=N<=10^5 
    1<=rating<=10^5 

    Output Format

    Output a single line containing the minimum number of candies Alice must buy.
  • Test Case 1
    Input (stdin)3
    1 2 2
    Expected Output4
  • Test Case 2
    Input (stdin)4
    2 1 2 4
    Expected Output8

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro