# Candy in C++

C++Server Side ProgrammingProgramming

Suppose there are N children, they are standing in a line. Here each child is assigned a rating value. We are supplying candies to these children subjected to the following requirements −

• Each child must have at least one candy.

• Children whose rating is high will get more candies than their neighbors.

We have to find the minimum number of candies we must give?

So if the input is like [1,1,3], then the output will be 4. So they will get 1, 1 and 2 candies respectively.

To solve this, we will follow these steps −

• n := size of the array ratings, create array called dp of size n, fill this using 1

• ret := 0

• for i in range 1 to n – 1

• if ratings[i] > ratings[i – 1], then dp[i] := dp[i - 1] + 1

• for i in range n - 2 down to 0

• if ratings[i] > ratings[i + 1], then dp[i] := max of dp[i] and dp[i + 1] + 1

• ret := sum of the elements of dp

• return ret

## Example (C++)

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector <int> dp(n, 1);
int ret = 0;
for(int i = 1; i < n; i++){
if(ratings[i] > ratings[i - 1]){
dp[i] = dp[i - 1] + 1;
}
}
for(int i = n - 2; i >= 0; i--){
if(ratings[i] > ratings[i + 1]){
dp[i] = max(dp[i], dp[i + 1] + 1);
}
}
for(int i = 0; i < n; i+=1){
ret += dp[i];
}
return ret;
}
};
main(){
Solution ob;
vector<int> v = {1,1,3};
cout << (ob.candy(v));
}

## Input

[1,1,3]

## Output

4
Published on 26-May-2020 16:46:37