leetcode->Candy

来源:互联网 发布:手机剪切视频的软件 编辑:程序博客网 时间:2024/05/21 10:32

<span style="font-family: Arial, Helvetica, sans-serif;">每日一刷,强迫学习</span>

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;

 第三步,从右向左扫,遇见当前等级比后一个高,但是糖果数比后一个低,则当前=后一个+1;


代码:

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package children;/** * * @author zhaoyufeng */public class Children {    public int candy(int[] ratings) {        int length = ratings.length;        int candySum = 0;        int[] candyEach = new int[length];        for (int i = 0; i < length; i++) {            candyEach[i] = 1;        }        for (int i = 1; i < length; i++) {            if (ratings[i] > ratings[i - 1]) {                candyEach[i] = candyEach[i - 1] + 1;            }        }        for (int i = length - 2; i >= 0; i--) {            if (ratings[i] > ratings[i + 1] && candyEach[i] <= candyEach[i + 1] ) {                candyEach[i] = candyEach[i + 1] + 1;            }        }        for (int i = 0; i <= length - 1; i++) {            System.out.print(" ratings[" + i + "]=" + ratings[i]);        }        System.out.println();        for (int i = 0; i <= length - 1; i++) {            System.out.print(" candyEach[" + i + "]=" + candyEach[i]);            candySum += candyEach[i];        }        System.out.println();        System.out.println(candySum);        return candySum;    }    /**     * @param args the command line arguments     */    public static void main(String[] args) {        // TODO code application logic here//        int a[] = {1, 2, 2, 4, 2, 1, 45, 3, 23, 2};        int a[] = {1,2,2};        Children child = new Children();        child.candy(a);    }}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 一年级小孩不爱做作业怎么办 小孩不愿多做作业怎么办 小孩一年级不自觉做作业怎么办 小孩会读不会写怎么办 好多字都不会写怎么办 写作业怎么办才能写快 五周宝宝爱玩不写字怎么办 爱玩手机的小孩怎么办? 一年级学生记不住生字怎么办 一年级小孩记不住生字怎么办 配镜度数高了怎么办 宝宝两岁半不肯坐马桶拉臭臭怎么办 儿子字写得不好 怎么办 小孩不听话不爱读书和写字怎么办 两岁宝宝不愿意穿衣服怎么办 做题粗心不认真怎么办 5岁宝宝不会写字怎么办 四岁宝宝不会写字怎么办 4岁宝宝不写字怎么办 四岁宝宝不写字怎么办 孩子学习粗心计算能力差怎么办 一年级的小朋友不爱看书怎么办 马上要生了害怕怎么办 孩子做题不爱读题怎么办 孩子作业写的慢怎么办 孩子学习不好怎么办我们有绝招 英语不会做题怎么办呢? 小学二年级孩子厌学怎么办 狗狗拉肚子不吃东西怎么办 小孩做作业时容易发呆怎么办 一上高速就犯困怎么办 孩子初中数学学不好怎么办 高三注意力不集中怎么办 考砸了家长打我怎么办? 高三学生困疲劳怎么办 高三晚上很困怎么办 孩子上高三压力大不想上学怎么办 高三的孩子压力大怎么办 高三复读压力大怎么办 孩子一年级做数学粗心怎么办 一年级的孩子数学总粗心怎么办