LeetCode: Candy 解题报告

Candy


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?

Hide Tags

SOLUTION:

使用一个数组记录每一个小孩应得的糖果的数目

1.我们可以从左往右扫描,如果遇到上升区间,就给小孩比左边多一个糖,否则就给1个糖果。

2.我们可以从右往左扫描,如果遇到上升区间,就给小孩比右边多一个糖,否则就给1个糖果。

   同时,应该与1步算出的值取一个大值(因为有可能要给小孩更多糖果才可以满足题设)。

 1 public class Solution {
 2     public int candy(int[] ratings) {
 3         if (ratings == null || ratings.length == 0) {
 4             return 0;
 5         }
 6         
 7         
 8         int len = ratings.length;
 9         int[] num = new int[len];
10         
11         // go from left to right;
12         for (int i = 0; i < len; i++) {
13             if (i > 0 && ratings[i] > ratings[i - 1]) {
14                 num[i] = num[i - 1] + 1;
15             } else {
16                 num[i] = 1;
17             }
18         }
19         
20         // go from right to left;
21         int sum = 0;
22         for (int i = len - 1; i >= 0; i--) {
23             if (i < len - 1 && ratings[i] > ratings[i + 1]) {
24                 num[i] = Math.max(num[i], num[i + 1] + 1);
25             }
26             sum += num[i];
27         }
28         
29         return sum;
30     }
31 }
View Code

CODE:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dp/Candy.java

原文地址:https://www.cnblogs.com/yuzhangcmu/p/4048980.html