zoukankan      html  css  js  c++  java
  • 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?

    有N个孩子站在一条线。分配给每个孩子一个评级的价值。

    你把糖果给这些孩子受到以下需求:

    每个孩子必须至少有一个糖果。

    评级较高的孩子得到更多的糖果比他们的邻居。

    什么是你必须给的最低糖果吗?

    以上内容是用有道翻译进行翻译

    解题思路:------------------------------------------

    每个小孩先发一块糖,然后从左向右进行遍历,如果arr[i]>arr[i-1],就在前一个人的糖的数目的基础上加1;

    最后从右往左遍历,加上所有的糖(从右往左遍历是考虑到权值为:7 5 8 9 6 4 12)的情况

     

    import java.util.*;
    public class Solution {
        public int candy(int[] ratings) {
            if(ratings==null || ratings.length==0) {
                return 0;
            }
             
            int[] count = new int[ratings.length];
            //每个孩子初始都有一个糖果
            Arrays.fill(count,1);
            int sum = 0;
            for(int i=1;i<ratings.length;i++) {
                if(ratings[i]>ratings[i-1]) {
                    count[i] = count[i-1]+1;
                }
            }
             
            for(int i=ratings.length-1;i>0;i--) {
                sum+=count[i];
                if(ratings[i]<ratings[i-1] && count[i]>=count[i-1]) {
                    count[i-1] = count[i]+1;
                }
            }
            sum+=count[0];
             
            return sum;
        }
    }
  • 相关阅读:
    神经网络之 --- 2012_ Alexnet
    Array.obj : error LNK2001: unresolved external symbol "void __cdecl Test_ultiply(void)" (?Test_ultiply@@YAXXZ)
    学习opencv出现配置错误(一)
    port和interface的区别
    Vivado当中的ooc与global模式
    ADC采样率,符号率
    MATLAB&Simulink的重复方式
    傅里叶变换的对称性质
    AXI总结一
    晶振相关(一)
  • 原文地址:https://www.cnblogs.com/googlemeoften/p/5826620.html
Copyright © 2011-2022 走看看