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?

    Cpp版本:

    class Solution {
    public:
        int candy(vector<int>& ratings) {
            int len = ratings.size();
            if (ratings.empty())
                return 0;
    
            if (len == 1)
                return 1;
    
            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] <= Candy[i+1])
                    Candy[i] = Candy[i + 1] + 1;
            }
            int ret = 0;
            for (int i = 0; i < len; i++) {
                ret += Candy[i];
            }
            return ret;
        }
    };

    Java:

    public class Solution {
        public int candy(int[] ratings) {
            int size = ratings.length;
            if (size == 0)    return 0;
            if (size == 1)  return 1;
    
            int[] Candy = new int[size];
    
            Candy[0] = 1;
            for (int i = 1; i < size; i++) {
                if (ratings[i] > ratings[i - 1])
                    Candy[i] = Candy[i - 1] + 1;
                else
                    Candy[i] = 1;
            }
    
            for (int i = size - 2; i >= 0; i--) {
                if (ratings[i] > ratings[i + 1] && Candy[i] <= Candy[i + 1]) {
                    Candy[i] = Candy[i + 1] + 1;
                }
            }
    
            int ret = 0;
            for (int i = 0; i < size; i++) {
                ret += Candy[i];
            }
            return ret;
        }
    }
  • 相关阅读:
    BZOJ1610: [Usaco2008 Feb]Line连线游戏
    BZOJ4554: [Tjoi2016&Heoi2016]游戏
    BZOJ3174: [Tjoi2013]拯救小矮人
    BZOJ3192: [JLOI2013]删除物品
    BZOJ3156: 防御准备
    BZOJ3875: [Ahoi2014&Jsoi2014]骑士游戏
    BZOJ 1597: [Usaco2008 Mar]土地购买
    洛谷 P3375 【模板】KMP字符串匹配
    洛谷 P3370 【模板】字符串哈希
    BZOJ 1083 繁忙的都市
  • 原文地址:https://www.cnblogs.com/wxquare/p/5207978.html
Copyright © 2011-2022 走看看