leetcode->Candy

<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);
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值