zoukankan      html  css  js  c++  java
  • 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 Solution {
        public int candy(int[] ratings) {
            int len = ratings.length;
            int count = 0;
            int[] candy = new int[len];
            candy[0] = 1;
            for(int i = 1; i < len; i++){
                if(ratings[i] > ratings[i-1]){
                    candy[i] = candy[i-1] +1;
                }else{
                    candy[i] = 1;
                }
            }
            
            for(int i = len-2; i>=0; i--){
                if(ratings[i] > ratings[i+1]){
                    candy[i] = Math.max(candy[i], candy[i+1]+1);
                }
            }
            
            for(int i = 0; i< candy.length; i++){
                count += candy[i];
            }
            
            return count;
        }
    }

    TODO------DP : http://fisherlei.blogspot.com/2013/11/leetcode-candy-solution.html

  • 相关阅读:
    sys模块
    os模块
    datetime模块
    time模块

    random模块
    python文件两种用途
    模块的搜索路径
    如何修改cnblogs的文本编辑器
    socket状态
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3553611.html
Copyright © 2011-2022 走看看