題目:
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?
題解:
這道題和Trapping water那個是一樣的想法,因為無論是水坑還是得到糖的小朋友,影響因素都不只一邊,都是左右兩邊的最小值/最大值來決定的。
所以這道題跟上一道一樣,也是左右兩邊遍歷陣列。
leftnums陣列存從左邊遍歷,當前小朋友對比其左邊小朋友,他能拿到糖的數量;
rightnums陣列存從右邊遍歷,當前小朋友對比其右邊小朋友,他能拿到的糖的數量。
最後針對這兩個陣列,每個小朋友能拿到的糖的數量就是這兩個數最大的那個數,求總加和就好了。
程式碼如下:
1 public int candy(int[] ratings) {
2 if(ratings==null || ratings.length==0)
3 return 0;
4
5 int[] leftnums = new int[ratings.length];
6 int[] rightnums = new int[ratings.length];
7
8 leftnums[0]=1;
9 for(int i=1;i<ratings.length;i++){
10 if(ratings[i]>ratings[i-1])
11 leftnums[i] = leftnums[i-1]+1;
12 else
13 leftnums[i] = 1;
14 }
15
16 rightnums[ratings.length-1] = leftnums[ratings.length-1];
17 for(int i=ratings.length-2;i>=0;i--){
18 if(ratings[i]>ratings[i+1])
19 rightnums[i] = rightnums[i+1]+1;
20 else
21 rightnums[i] = 1;
22
23 }
24
25 int res = 0;
26 for(int i = 0; i<ratings.length; i++)
27 res += Math.max(leftnums[i],rightnums[i]);
28
29 return res;
30 }
2 if(ratings==null || ratings.length==0)
3 return 0;
4
5 int[] leftnums = new int[ratings.length];
6 int[] rightnums = new int[ratings.length];
7
8 leftnums[0]=1;
9 for(int i=1;i<ratings.length;i++){
10 if(ratings[i]>ratings[i-1])
11 leftnums[i] = leftnums[i-1]+1;
12 else
13 leftnums[i] = 1;
14 }
15
16 rightnums[ratings.length-1] = leftnums[ratings.length-1];
17 for(int i=ratings.length-2;i>=0;i--){
18 if(ratings[i]>ratings[i+1])
19 rightnums[i] = rightnums[i+1]+1;
20 else
21 rightnums[i] = 1;
22
23 }
24
25 int res = 0;
26 for(int i = 0; i<ratings.length; i++)
27 res += Math.max(leftnums[i],rightnums[i]);
28
29 return res;
30 }