Problem statement:
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:
1. Each child must have at least one candy.
2. Children with a higher rating get more candies than their neighbors.
2. Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
June 8, 2015
Read the websites in my favorite orders:
Analysis from website 2
This problem can be solved in O(n) time.
We can always assign a neighbor with 1 more if the neighbor has higher a rating value. However, to get the minimum total number, we should always start adding 1s in the ascending order. We can solve this problem by scanning the array from both sides. First, scan the array from left to right, and assign values for all the ascending pairs. Then scan from right to left and assign values to descending pairs.
This problem is similar to Trapping Rain Water.
Most important, play with code; Spent 30 minutes to work on the coding using C# (change from Java code on webpage 2), and also, the code passes leetcode online judge.
https://github.com/jianminchen/candy/blob/master/Program.cs
No comments:
Post a Comment