forked from Prashantsingh-8/CCC-Traning-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ques-19
73 lines (66 loc) · 1.83 KB
/
Ques-19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
Q-19) 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?
Input Format
First line contains an integer N.
Next line contains N space separated integers.
Constraints
1 <= N <= 106
1 <= Ai <= 103
Output Format
Output the minimum number of candies you can give out.
Sample Input 0
2
1 2
Sample Output 0
3
Explanation 0
The candidate with 1 rating gets 1 candy and candidate with rating cannot get 1 candy as 1 is its neighbor. So rating 2 candidate gets 2 candies. In total, 2+1 = 3 candies need to be given out.
CODE:
#include<bits/stdc++.h>
using namespace std;
int findSolution(vector<int> &ratings)
{
int size = ratings.size();
if(size==0)
return 0;
vector<int> leftToRight(size);
vector<int> rightToLeft(size);
int sum;
leftToRight[0] = 1;
for(int i=1;i<size;i++)
{
if(ratings[i]>ratings[i-1])
leftToRight[i] = leftToRight[i-1]+1;
else
leftToRight[i] = 1;
}
sum=leftToRight[size-1];
rightToLeft[size-1] = 1;
for(int i=size-2;i>=0;i--)
{
if(ratings[i]>ratings[i+1])
rightToLeft[i] = rightToLeft[i+1]+1;
else
rightToLeft[i] = 1;
sum+=(leftToRight[i]>rightToLeft[i]?leftToRight[i]:rightToLeft[i]);
}
return sum;
}
int main()
{
int n,i;
//cout<<"Enter the number of children ";
cin>>n;
vector<int> a(n);
//cout<<"Enter the rating of each child"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
//cout<<"The Minimum number of candies Alice must buy is "<<endl;
cout<<findSolution(a)<<endl;
return 0;
}