• 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;
        }
    }
  • 相关阅读:
    core--线程同步(用户模式)
    Android-Kotlin-Activity直接的跳转
    Android-Kotlin-枚举enum
    Android-Kotlin-单例模式
    Android-Kotlin-代理和委托
    Android-Kotlin-接口与多态的表现
    Android-Kotlin-set/get方法的使用
    Android-Kotlin-继承
    Android-Kotlin简单计算器功能
    CentOS 6.5 X64 U盘启动盘制作
  • 原文地址:https://www.cnblogs.com/wxquare/p/5207978.html
Copyright © 2020-2023  润新知