1. 程式人生 > >[Leetcode 135]糖果分配 Candy

[Leetcode 135]糖果分配 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?

分糖果,【權值大】的人分的糖果比左右多。權值相同,糖果可多可少可相等。

【思路】

新建陣列全部初始化1,至少分到一個糖果。

從左到右、從右到左兩次遍歷陣列

【程式碼】

陣列賦值和迴圈可以改進

最初版本

class Solution {
    public int candy(int[] ratings) {
        int sum=0;
        int []tmp=new int[ratings.length];
        for(int i=0;i<ratings.length;i++){
            tmp[i]
=1; } for(int i=1;i<ratings.length;i++){ if(ratings[i]>ratings[i-1]){ tmp[i]=tmp[i-1]+1; } } for(int i=ratings.length-2;i>=0;i--){ if(ratings[i]>ratings[i+1]){ tmp[i]=Math.max(tmp[i],tmp[i+1]+1); } }
for(int i=0;i<tmp.length;i++){ sum+=tmp[i]; } return sum; } }

【改進】

陣列賦值

        for(int i=0;i<ratings.length;i++){
            tmp[i]=1;
        }

等價於

 Arrays.fill(tmp, 1);