算法系列——Candy

来源:互联网 发布:头脑风暴软件 编辑:程序博客网 时间:2024/06/05 00:35

题目描述

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?

解题思路

贪心算法的运用,双向爬坡。从左到右爬一边,再从右到左爬一边。再累加所有值即可。

程序实现

public class Solution {    public int candy(int[] ratings) {        int len=ratings.length;        int [] candys=new int[len];        //每人先至少分一个        Arrays.fill(candys,1);        //从左到右,保证如果右边的ratings值大于左边,candy的也要大些        for(int i=1;i<len;i++){            if(ratings[i]>ratings[i-1])                candys[i]=candys[i-1]+1;        }        //从右到左,保证如果左边的ratings值大于右边,candy的也要大些        for(int i=len-2;i>=0;i--){            if(ratings[i]>ratings[i+1]&&candys[i]<=candys[i+1])                candys[i]=candys[i+1]+1;        }         //累加结果        int sum=0;        for(int i=0;i<len;i++)            sum+=candys[i];        return sum;    }}
原创粉丝点击