Skip to content

Instantly share code, notes, and snippets.

@schauhan232
Last active July 15, 2021 07:19
Show Gist options
  • Save schauhan232/a1fc398a0f39e5ead3e2c5ee40bd9c91 to your computer and use it in GitHub Desktop.
Save schauhan232/a1fc398a0f39e5ead3e2c5ee40bd9c91 to your computer and use it in GitHub Desktop.
Distribute Candy Problem
There are N children standing in a line with some rating value. You want to distribute a minimum number of candies to these children such that:
Each child must have at least one candy.
The children with higher ratings will have more candies than their neighbors.
You need to write a program to calculate the minimum candies you must give.
class Program
{
public static void Main(string[] args)
{
var ratings = new int[] { 1, 5, 2, 1 };
var leftArray = Enumerable.Repeat(1, ratings.Length).ToArray();
var rightArray = Enumerable.Repeat(1, ratings.Length).ToArray();
var left = 1;
while (left < ratings.Length)
{
if (ratings[left] > ratings[left - 1])
leftArray[left] = leftArray[left - 1] + 1;
left++;
}
var right = ratings.Length - 2;
while (right >= 0)
{
if (ratings[right] > ratings[right + 1])
rightArray[right] = rightArray[right + 1] + 1;
right--;
}
var max = 0;
for (int i = 0; i < ratings.Length; i++)
{
max = max + Math.Max(leftArray[i], rightArray[i]);
}
Console.WriteLine(max);
Console.Read();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment