[Leetcode] Candy (Java)

来源:互联网 发布:淘宝直通车 转化率多少 编辑:程序博客网 时间:2024/05/16 04:37

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) {        if(ratings.length==0)return 0;int ret = ratings.length;int[] candy = new int[ratings.length];int k=1;for(int i=1;i<candy.length;i++){if(ratings[i]>ratings[i-1])candy[i]=k++;else k=1;}k=1;for(int i=candy.length-2;i>=0;i--){if(ratings[i]>ratings[i+1])candy[i]=Math.max(k++,candy[i]);else k=1;}for(int i=0;i<candy.length;i++){ret+=candy[i];}return ret;    }}


0 0
原创粉丝点击