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.
OR
MegaCorp wants to give bonuses to its employees based on how many lines of codes they have written. They would like to give the smallest positive amount to each worker consistent with the constraint that if a developer has written more lines of code than their neighbor, they should receive more money.
Given an array representing a line of seats of employees at MegaCorp, determine how much each one should get paid.
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
|
|
|
|
|
|
|
|