码迷,mamicode.com
首页 > 其他好文 > 详细

Candy 解答

时间:2015-10-08 06:50:36      阅读:373      评论:0      收藏:0      [点我收藏+]

标签:

Question

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:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?

Solution

Key to the problem is to consider the whole array as combination of many ascending sub-arrays and descending sub-arrays. So when we solve candy distribution problems among these sub-arrays, the whole problem is solved.

There are some points to note:

1. To find descending sub-array like 5, 4, 3, 2, 1, we can traverse from right to left. In this way, the sub-array is ascending.

2. For each peek, like 5 in 1, 2, 3, 4, 5, 4, 1, we need compare its previous candy number with current candy number.

Example

技术分享

 1 public class Solution {
 2     public int candy(int[] ratings) {
 3         if (ratings == null || ratings.length < 1)
 4             return 0;
 5         int length = ratings.length;
 6         if (length == 1)
 7             return 1;
 8         int[] candyNum = new int[length];
 9         candyNum[0] = 1;
10         int result = 0;
11         int index = 1;
12         // First, process ascending sub-array
13         while (index < length) {
14             if (ratings[index] > ratings[index - 1])
15                 candyNum[index] = candyNum[index - 1] + 1;
16             else
17                 candyNum[index] = 1;
18             index++;
19         }
20         
21         // Then, process descending sub-array
22         index = length - 2;
23         result = candyNum[length - 1];
24         while (index >= 0) {
25             if (ratings[index] > ratings[index + 1])
26                 // Here, we need compare
27                 candyNum[index] = Math.max(candyNum[index + 1] + 1, candyNum[index]);
28             result += candyNum[index];
29             index--;
30         }
31         
32         return result;
33     }
34 }

 

Candy 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4859955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!