• 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");
        }
    }
    
  • 相关阅读:
    springMVC 错误页面配置
    设计模式 11 —— 代理模式
    JAVA RMI 实例
    设计模式 10 —— 状态模式
    设计模式 9 —— 模板方法模式
    Java EE : 三、图解Session(会话)
    Java EE : 二、图解 Cookie(小甜饼)
    Java EE : 一、图解Http协议
    《JAVA与模式》之单例模式
    Java中如何克隆集合——ArrayList和HashSet深拷贝
  • 原文地址:https://www.cnblogs.com/sunshine-2015/p/7887178.html
Copyright © 2020-2023  润新知