Candy
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?
Code :
int candy(vector<int> &A) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int n = A.size();
if(n < 2)
return n;
bool allDone = false;
int candies = 0;
vector<int> c(n,0);
while(!allDone){
allDone = true;
int i = 0;
while(i < n){
if(c[i] == 0){
int left,right;
if(i == n - 1)
right = INT_MAX;
else
right = A[i + 1];
if(i == 0)
left = INT_MAX;
else
left = A[i - 1];
if(A[i] <= left && A[i] <= right){
int num = 1;
c[i] = num;candies += num;allDone = false;
}
else if(A[i] <= left && A[i] > right){
if(c[i + 1] != 0){
int num = c[i + 1] + 1;
c[i] = num;candies += num;allDone = false;
}
}
else if(A[i] > left && A[i] <= right){
if(c[i - 1] != 0){
int num = c[i - 1] + 1;
c[i] = num;candies += num;allDone = false;
}
}
else{
if(c[i + 1] != 0 && c[i - 1] != 0){
int num = max(c[i + 1],c[i - 1]) + 1;
c[i] = num;candies += num;allDone = false;
}
}
}
i = i + 1;
}
}
return candies;
}
No comments:
Post a Comment