Problem
There are n
children standing in a line. Each child is assigned a rating value given in the integer array ratings
.
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.
Return the minimum number of candies you need to have to distribute the candies to the children.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3
|
|
Solution
Method 1 - Brute Force
A simple solution is to generate all subsets of size m of arr[0..n-1]. For every subset, find the difference between maximum and minimum elements in it. Finally return minimum difference.
Lets to better.
Method 2 - Scan From Left and Right
The problem is similar to Trapping Rain Water.
- Do it in two directions.
- The first loop makes sure children with a higher rating get more candy than its left neighbour;
- The second loop makes sure children with a higher rating get more candy than its right neighbour. Because we have already distributed candies, to right neighbour, if it is not already max between them.
Code
|
|
|
|
|
|
|
|