zoukankan      html  css  js  c++  java
  • leetcode — candy

    /**
     * Source : https://oj.leetcode.com/problems/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?
     *
     */
    public class Candy {
    
        /**
         * 给站成一排的孩子分糖果,
         * 每个孩子至少一个
         * 每个孩子的权重不一样,权重高的孩子比相邻的孩子要多
         * 求最少需要多少个糖果
         *
         * 从左到右遍历,寻找递增序列,该位置对应的孩子分的糖果数也递增,每个递增序列从1开始,这样保证了rating高的孩子比左边的孩子多
         * 然后从右向左遍历,确保当前位置孩子的糖果数多于右边孩子的
         * 复杂度为O(n)
         *
         * @param ratings
         * @return
         */
        public int candy (int[] ratings) {
            if (ratings.length <= 0) {
                return 0;
            }
            int[] candy = new int[ratings.length];
            candy[0] = 1;
            for (int i = 1; i < ratings.length; i++) {
                if (ratings[i] > ratings[i-1]) {
                    candy[i] = candy[i-1] + 1;
                } else {
                    candy[i] = 1;
                }
            }
            int sum = candy[ratings.length-1];
            for (int i = ratings.length-2; i > -1; i--) {
                if (ratings[i] > ratings[i+1] && candy[i] <= candy[i+1]) {
                    candy[i] = candy[i+1] + 1;
                }
                sum += candy[i];
            }
            return sum;
        }
    
        public static void main(String[] args) {
            Candy candy = new Candy();
            int[] ratings = new int[]{5, 6, 7, 4, 1, 2, 3, 2, 1, 7};
            System.out.println(candy.candy(ratings) + " == 19");
        }
    }
    
  • 相关阅读:
    Spring注解驱动开发(二)--组件注入
    Spring注解驱动开发(一)--项目搭建
    Font "微软雅黑" is not available to the JVM. See the Javadoc for more details.
    idea下远程debug调试
    JasperReport生成PDF文件
    Java获取系统属性和环境变量
    oracle date change
    winform webbrowser flash显示
    uploadify参数
    对COM 组件的调用返回了错误 HRESULT E_FAIL
  • 原文地址:https://www.cnblogs.com/sunshine-2015/p/7887178.html
Copyright © 2011-2022 走看看