北京林业大学“计蒜客”杯程序设计竞赛 网络赛 . candy

题目回忆版:
原来是leetcode原题【LeetCode】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?

多个小朋友站成一排,根据他们的得分分发糖果,得分高的小朋友要比旁边得分低的小朋友得到的糖果多,每个小朋友至少得到一枚糖果,问最少要准备多少糖果?
【数据】:
5
1 2 3 4 5
15
【思路】

先从左到右扫描一遍,使得右边比左边得分高的小朋友糖果数比左边多。

再从右到左扫描一遍,使得左边比右边得分高的小朋友糖果数比右边多。

【代码】:

public class Solution {
    public int candy(int[] ratings) {

        int size= ratings.length;
        if(size ==0) return -1;
        if(size ==1) return 1;

        int [] ans = new int [size];
        ans[0]=1;
        //正向扫描一遍,如果右边的rating比左边高,那么右边的糖果数就比左边多一个,否则只给一个糖果 
        for(int i=1; i<size ; ++i)
        {
            if(ratings[i] >ratings[i-1]) ans[i]=ans[i-1]+1;
            else ans[i]=1;
        }

        //反向扫描一遍,如果左边的rating比右边高,并且左边的糖果数比右边少,那么左边的糖果数应比右边多一 
        for(int i=size-2; i>=0; --i)
        {
            if(ratings[i]> ratings[i+1] && ans[i] <= ans[i+1])
            {
                ans[i]=ans[i+1]+1;
            }
        }

        int sum=0;
        for(int i=0; i<size; ++i)
        {
            sum+=ans[i];
        }
        return sum;
    }
}

你可能感兴趣的:(LeetCode)