A line of N kids is standing there. The rating values listed in the integer array ratings are assigned to each kid.
These kids are receiving candy, according to the following criteria:
1) There must be at least one candy for every child.
2) Kids whose scores are higher than their neighbours receive more candies than their neighbours.
Return the minimum number of candies needed to distribute among children.
Input : ratings = [1, 0, 5]
Output : 5
Explanation : The distribution of candies will be 2 , 1 , 2 to first , second , third child respectively.
Input : ratings = [1, 2, 2]
Output : 4
Explanation : The distribution of candies will be 1 , 2 , 1 to first , second , third child respectively.
The third gets only 1 candy because it satisfy above two criteria.
Input : ratings = [1, 2, 1, 4, 5]
Checking for the maximum from the left and right arrays and summing them up
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// To calculate number of candies
int candy(vector<int>& ratings) {
// Get number of children
int n = ratings.size();
// If no children, return 0
if (n == 0) return 0;
/*Initialize vectors to store candies
for each child from left and right*/
vector<int> left(n, 1);
vector<int> right(n, 1);
/*Left to right pass
Traverse the ratings from left to right
to adjust candies based on ratings*/
for (int i = 1; i < n; ++i) {
/*If the current child's rating is
higher than the previous one*/
if (ratings[i] > ratings[i - 1]) {
/*Give the current child one
more candy than the previous one*/
left[i] = left[i - 1] + 1;
}
}
/*Right to left pass
Traverse the ratings from right to left
to adjust candies based on ratings*/
for (int i = n - 2; i >= 0; --i) {
/* If the current child's rating is
higher than the next one*/
if (ratings[i] > ratings[i + 1]) {
/* Give the current child one
more candy than the next one*/
right[i] = right[i + 1] + 1;
}
}
/*Combine results
Calculate the total number of candies
needed by taking the maximum from
left and right for each child*/
int ans = 0;
for (int i = 0; i < n; ++i) {
/*Each child gets the maximum
candies from left and right*/
ans += max(left[i], right[i]);
}
// Return total
return ans;
}
};
int main() {
vector<int> ratings = {1, 0, 2};
Solution sol;
int result = sol.candy(ratings);
cout << "Minimum candies required: " << result << endl;
return 0;
}
import java.util.*;
class Solution {
// To calculate number of candies
public int candy(int[] ratings) {
// Get number of children
int n = ratings.length;
// If no children, return 0
if (n == 0) return 0;
/*Initialize arrays to store candies
for each child from left and right*/
int[] left = new int[n];
int[] right = new int[n];
Arrays.fill(left, 1);
Arrays.fill(right, 1);
/*Left to right pass
Traverse the ratings from left to right
to adjust candies based on ratings*/
for (int i = 1; i < n; ++i) {
/*If the current child's rating is
higher than the previous one*/
if (ratings[i] > ratings[i - 1]) {
/*Give the current child one
more candy than the previous one*/
left[i] = left[i - 1] + 1;
}
}
/*Right to left pass
Traverse the ratings from right to left
to adjust candies based on ratings*/
for (int i = n - 2; i >= 0; --i) {
/*If the current child's rating is
higher than the next one*/
if (ratings[i] > ratings[i + 1]) {
/*Give the current child one
more candy than the next one*/
right[i] = right[i + 1] + 1;
}
}
/*Combine results
Calculate the total number of candies
needed by taking the maximum from
left and right for each child*/
int ans = 0;
for (int i = 0; i < n; ++i) {
/*Each child gets the maximum
candies from left and right*/
ans += Math.max(left[i], right[i]);
}
// Return total
return ans;
}
public static void main(String[] args) {
int[] ratings = {1, 0, 2};
Solution sol = new Solution();
int result = sol.candy(ratings);
System.out.println("Minimum candies required: " + result);
}
}
class Solution:
# To calculate number of candies
def candy(self, ratings):
# Get number of children
n = len(ratings)
# If no children, return 0
if n == 0:
return 0
# Initialize lists to store candies
# for each child from left and right
left = [1] * n
right = [1] * n
# Left to right pass
# Traverse the ratings from left to right
# to adjust candies based on ratings
for i in range(1, n):
# If the current child's rating is
# higher than the previous one
if ratings[i] > ratings[i - 1]:
# Give the current child one
# more candy than the previous one
left[i] = left[i - 1] + 1
# Right to left pass
# Traverse the ratings from right to left
# to adjust candies based on ratings
for i in range(n - 2, -1, -1):
# If the current child's rating is
# higher than the next one
if ratings[i] > ratings[i + 1]:
# Give the current child one
# more candy than the next one
right[i] = right[i + 1] + 1
# Combine results
# Calculate the total number of candies
# needed by taking the maximum from
# left and right for each child
ans = 0
for i in range(n):
# Each child gets the maximum
# candies from left and right
ans += max(left[i], right[i])
# Return total
return ans
if __name__ == "__main__":
ratings = [1, 0, 2]
sol = Solution()
result = sol.candy(ratings)
print("Minimum candies required:", result)
class Solution {
// To calculate number of candies
candy(ratings) {
// Get number of children
const n = ratings.length;
// If no children, return 0
if (n === 0) return 0;
/*Initialize arrays to store candies
for each child from left and right*/
const left = new Array(n).fill(1);
const right = new Array(n).fill(1);
/*Left to right pass
Traverse the ratings from left to right
to adjust candies based on ratings*/
for (let i = 1; i < n; ++i) {
/*If the current child's rating is
higher than the previous one*/
if (ratings[i] > ratings[i - 1]) {
/*Give the current child one
more candy than the previous one*/
left[i] = left[i - 1] + 1;
}
}
/*Right to left pass
Traverse the ratings from right to left
to adjust candies based on ratings*/
for (let i = n - 2; i >= 0; --i) {
/*If the current child's rating is
higher than the next one*/
if (ratings[i] > ratings[i + 1]) {
/*Give the current child one
more candy than the next one*/
right[i] = right[i + 1] + 1;
}
}
/*Combine results
Calculate the total number of candies
needed by taking the maximum from
left and right for each child*/
let ans = 0;
for (let i = 0; i < n; ++i) {
/*Each child gets the maximum
candies from left and right*/
ans += Math.max(left[i], right[i]);
}
// Return total
return ans;
}
}
const ratings = [1, 0, 2];
const sol = new Solution();
const result = sol.candy(ratings);
console.log("Minimum candies required:", result);
As, we need to consider both the left and right neighbours, what we can do is take a 'left' array and store the minimum number of candies for each child based on the ratings of left neighbours. Now for the candies based on the rating of right neighbour, we can take take a 'right' variable which will keep track of the candies that the right neighbour own. Thus in each iteration we will have number of candies of both the left and right neighbours, using both of them we can calculate 'cur' and add it to the answer.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// To calculate number of candies
int candy(vector<int>& ratings) {
// Get number of children
int n = ratings.size();
// If no children, return 0
if (n == 0) return 0;
/*Initialize vectors to store candies
for each child from left and right*/
vector<int> left(n, 1);
/*Left to right pass
Traverse the ratings from left to right
to adjust candies based on ratings*/
for (int i = 1; i < n; ++i) {
/*If the current child's rating is
higher than the previous one*/
if (ratings[i] > ratings[i - 1]) {
/*Give the current child one
more candy than the previous one*/
left[i] = left[i - 1] + 1;
}
}
int cur = 1;
int right = 1;
int sum = max(1, left[n-1]);
/*Right to left pass
Traverse the ratings from right to left
to adjust candies based on ratings*/
for (int i = n - 2; i >= 0; --i) {
/* If the current child's rating is
higher than the next one*/
if (ratings[i] > ratings[i + 1]) {
/* Give the current child one
more candy than the next one*/
cur = right + 1;
}
else{
cur = 1;
}
right = cur;
sum = sum + max(left[i], cur);
}
// Return total
return sum;
}
};
int main() {
vector<int> ratings = {1, 0, 2};
Solution sol;
int result = sol.candy(ratings);
cout << "Minimum candies required: " << result << endl;
return 0;
}
import java.util.*;
public class Solution {
// To calculate number of candies
public int candy(int[] ratings) {
// Get number of children
int n = ratings.length;
// If no children, return 0
if (n == 0) return 0;
/*Initialize vectors to store candies
for each child from left and right*/
int[] left = new int[n];
Arrays.fill(left, 1);
/*Left to right pass
Traverse the ratings from left to right
to adjust candies based on ratings*/
for (int i = 1; i < n; ++i) {
/*If the current child's rating is
higher than the previous one*/
if (ratings[i] > ratings[i - 1]) {
/*Give the current child one
more candy than the previous one*/
left[i] = left[i - 1] + 1;
}
}
int cur = 1;
int right = 1;
int sum = Math.max(1, left[n-1]);
/*Right to left pass
Traverse the ratings from right to left
to adjust candies based on ratings*/
for (int i = n - 2; i >= 0; --i) {
/* If the current child's rating is
higher than the next one*/
if (ratings[i] > ratings[i + 1]) {
/* Give the current child one
more candy than the next one*/
cur = right + 1;
}
else{
cur = 1;
}
right = cur;
sum = sum + Math.max(left[i], cur);
}
// Return total
return sum;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] ratings = {1, 0, 2};
//Creating an instance of Solution class
int result = sol.candy(ratings);
System.out.println("Minimum candies required: " + result);
}
}
class Solution:
# To calculate number of candies
def candy(self, ratings):
# Get number of children
n = len(ratings)
# If no children, return 0
if n == 0:
return 0
""" Initialize vectors to store candies
for each child from left and right"""
left = [1] * n
# Left to right pass
for i in range(1, n):
""" If the current child's rating
is higher than the previous one"""
if ratings[i] > ratings[i - 1]:
""" Give the current child one
more candy than the previous one"""
left[i] = left[i - 1] + 1
cur = 1
right = 1
sum_candies = max(1, left[n - 1])
# Right to left pass
for i in range(n - 2, -1, -1):
""" If the current child's rating
is higher than the next one"""
if ratings[i] > ratings[i + 1]:
""" Give the current child one
more candy than the next one"""
cur = right + 1
else:
cur = 1
right = cur
sum_candies += max(left[i], cur)
# Return total
return sum_candies
if __name__ == "__main__":
sol = Solution()
ratings = [1, 0, 2]
result = sol.candy(ratings)
print(f"Minimum candies required: {result}")
class Solution {
// To calculate number of candies
candy(ratings) {
// Get number of children
let n = ratings.length;
// If no children, return 0
if (n === 0) return 0;
/* Initialize arrays to store candies
for each child from left and right */
let left = new Array(n).fill(1);
/* Left to right pass
Traverse the ratings from left to right
to adjust candies based on ratings */
for (let i = 1; i < n; ++i) {
/* If the current child's rating is
higher than the previous one */
if (ratings[i] > ratings[i - 1]) {
/* Give the current child one
more candy than the previous one */
left[i] = left[i - 1] + 1;
}
}
let cur = 1;
let right = 1;
let sum = Math.max(1, left[n - 1]);
/* Right to left pass
Traverse the ratings from right to left
to adjust candies based on ratings */
for (let i = n - 2; i >= 0; --i) {
/* If the current child's rating is
higher than the next one */
if (ratings[i] > ratings[i + 1]) {
/* Give the current child one
more candy than the next one */
cur = right + 1;
} else {
cur = 1;
}
right = cur;
sum += Math.max(left[i], cur);
}
// Return total
return sum;
}
}
const sol = new Solution();
const ratings = [1, 0, 2];
const result = sol.candy(ratings);
console.log("Minimum candies required: " + result);
Calculating candies according to the trend
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// To calculate the number of candies
int candy(vector<int>& ratings) {
// Size of the ratings array
int n = ratings.size();
// Initialize index variable
int i = 1;
/*Initialize the total number of candies,
starting with one candy for the first child*/
int sum = 1;
// Loop the ratings array
while (i < n) {
/*Check if the current child's rating
is equal to the previous one*/
if (ratings[i] == ratings[i - 1]) {
/* If so, give the current child one
more candy than the previous one*/
sum = sum + 1;
/* Move to the next child*/
i++;
/*Skip the rest of the loop and
move to the next iteration*/
continue;
}
/* Initialize the candy count
for increasing rating trend*/
int peak = 1;
// Loop through increasing ratings trend
while (i < n && ratings[i] > ratings[i - 1]) {
/*Increment candy count
for increasing trend*/
peak += 1;
/*Update the total
number of candies*/
sum += peak;
// Move to next
i++;
}
/*Initialize the candy count
for decreasing rating trend*/
int down = 1;
// Loop through decreasing ratings trend
while (i < n && ratings[i] < ratings[i - 1]) {
/*Update the total number of
candies for decreasing trend*/
sum += down;
// Move to next
i++;
/*Increment the candy
count for decreasing trend*/
down++;
}
/*Check if the candy count for
decreasing trend exceeds the peak*/
if (down > peak) {
/*Adjust the total number of
candies to satisfy the condition*/
sum += (down - peak);
}
}
// Return total candies
return sum;
}
};
int main() {
vector<int> ratings = {0, 2, 4, 3, 2, 1, 1, 3, 4, 6, 4, 0, 0};
cout << "Ratings of Children: ";
for(int i = 0; i < ratings.size(); i++){
cout << ratings[i] << " ";
}
cout << endl;
Solution sol;
int result = sol.candy(ratings);
cout << "Minimum number of candies needed: " << result << endl;
return 0;
}
import java.util.*;
class Solution {
// To calculate the number of candies
public int candy(int[] ratings) {
// Size of the ratings array
int n = ratings.length;
// Initialize index variable
int i = 1;
/*Initialize the total number of candies,
starting with one candy for the first child*/
int sum = 1;
// Loop the ratings array
while (i < n) {
/*Check if the current child's rating
is equal to the previous one*/
if (ratings[i] == ratings[i - 1]) {
/* If so, give the current child one
more candy than the previous one*/
sum = sum + 1;
/* Move to the next child*/
i++;
/*Skip the rest of the loop and
move to the next iteration*/
continue;
}
/* Initialize the candy count
for increasing rating trend*/
int peak = 1;
// Loop through increasing ratings trend
while (i < n && ratings[i] > ratings[i - 1]) {
/*Increment candy count
for increasing trend*/
peak += 1;
/*Update the total
number of candies*/
sum += peak;
// Move to next
i++;
}
/*Initialize the candy count
for decreasing rating trend*/
int down = 1;
// Loop through decreasing ratings trend
while (i < n && ratings[i] < ratings[i - 1]) {
/*Update the total number of
candies for decreasing trend*/
sum += down;
// Move to next
i++;
/*Increment the candy
count for decreasing trend*/
down++;
}
/*Check if the candy count for
decreasing trend exceeds the peak*/
if (down > peak) {
/*Adjust the total number of
candies to satisfy the condition*/
sum += (down - peak);
}
}
// Return total candies
return sum;
}
public static void main(String[] args) {
int[] ratings = {0, 2, 4, 3, 2, 1, 1, 3, 4, 6, 4, 0, 0};
System.out.print("Ratings of Children: ");
for(int rating : ratings){
System.out.print(rating + " ");
}
System.out.println();
Solution sol = new Solution();
int result = sol.candy(ratings);
System.out.println("Minimum number of candies needed: " + result);
}
}
class Solution:
# To calculate the number of candies
def candy(self, ratings):
# Size of the ratings array
n = len(ratings)
# Initialize index variable
i = 1
'''Initialize the total number of candies,
starting with one candy for the first child'''
sum = 1
# Loop the ratings array
while i < n:
'''Check if the current child's rating
is equal to the previous one'''
if ratings[i] == ratings[i - 1]:
'''If so, give the current child one
more candy than the previous one'''
sum += 1
'''Move to the next child'''
i += 1
'''Skip the rest of the loop and
move to the next iteration'''
continue
'''Initialize the candy count
for increasing rating trend'''
peak = 1
# Loop through increasing ratings trend
while i < n and ratings[i] > ratings[i - 1]:
'''Increment candy count
for increasing trend'''
peak += 1
'''Update the total
number of candies'''
sum += peak
# Move to next
i += 1
'''Initialize the candy count
for decreasing rating trend'''
down = 1
# Loop through decreasing ratings trend
while i < n and ratings[i] < ratings[i - 1]:
'''Update the total number of
candies for decreasing trend'''
sum += down
# Move to next
i += 1
'''Increment the candy
count for decreasing trend'''
down += 1
'''Check if the candy count for
decreasing trend exceeds the peak'''
if down > peak:
'''Adjust the total number of
candies to satisfy the condition'''
sum += (down - peak)
# Return total candies
return sum
if __name__ == "__main__":
ratings = [0, 2, 4, 3, 2, 1, 1, 3, 4, 6, 4, 0, 0]
print("Ratings of Children: ", ratings)
sol = Solution()
result = sol.candy(ratings)
print("Minimum number of candies needed:", result)
class Solution {
// To calculate the number of candies
candy(ratings) {
// Size of the ratings array
const n = ratings.length;
// Initialize index variable
let i = 1;
/*Initialize the total number of candies,
starting with one candy for the first child*/
let sum = 1;
// Loop the ratings array
while (i < n) {
/*Check if the current child's rating
is equal to the previous one*/
if (ratings[i] === ratings[i - 1]) {
/* If so, give the current child one
more candy than the previous one*/
sum += 1;
/* Move to the next child*/
i++;
/*Skip the rest of the loop and
move to the next iteration*/
continue;
}
/* Initialize the candy count
for increasing rating trend*/
let peak = 1;
// Loop through increasing ratings trend
while (i < n && ratings[i] > ratings[i - 1]) {
/*Increment candy count
for increasing trend*/
peak += 1;
/*Update the total
number of candies*/
sum += peak;
// Move to next
i++;
}
/*Initialize the candy count
for decreasing rating trend*/
let down = 1;
// Loop through decreasing ratings trend
while (i < n && ratings[i] < ratings[i - 1]) {
/*Update the total number of
candies for decreasing trend*/
sum += down;
// Move to next
i++;
/*Increment the candy
count for decreasing trend*/
down++;
}
/*Check if the candy count for
decreasing trend exceeds the peak*/
if (down > peak) {
/*Adjust the total number of
candies to satisfy the condition*/
sum += (down - peak);
}
}
// Return total candies
return sum;
}
}
const ratings = [0, 2, 4, 3, 2, 1, 1, 3, 4, 6, 4, 0, 0];
console.log("Ratings of Children: ", ratings);
const sol = new Solution();
const result = sol.candy(ratings);
console.log("Minimum number of candies needed: ", result);
Q: What happens if multiple kids have the same rating?
A: If two kids have the same rating, they don’t need more candies than each other. Both can have the same number of candies, and no extra adjustments are needed.
Q: What if all kids have the same rating?
A: If all kids have the same rating, give each child exactly one candy. The total number of candies needed will be equal to the number of children.
Q: What if the ratings are very large?
A: The ratings do not directly affect the time or space complexity, as the algorithm only compares relative values and doesn’t perform any operations based on the magnitude of the ratings.
Q: How would you handle cases where multiple constraints are applied (e.g., candies must also be within a budget)?
A: Combine the current solution with a dynamic programming or optimization approach to satisfy additional constraints like budgets or candy limits.