zoukankan      html  css  js  c++  java
  • [leetcode-135-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?

    思路很朴素:两次遍历,从前往后和从后往前遍历。

    int candy(vector<int>& ratings)
        {
            if (ratings.size() == 0) return 0;
        //    sort(ratings.begin(), ratings.end());
            int sum = 0;//第一个为1
            vector<int>candyvec(ratings.size(),1);
            for (int i = 1; i < ratings.size();i++)
            {
                if (ratings[i] > ratings[i-1])//如果相等
                {
                    candyvec[i] = candyvec[i - 1]+1;
                }
                else
                {
                    candyvec[i] = 1;//最少1个
                }
            }
            sum = candyvec[ratings.size() - 1];
            for (int i = ratings.size() - 2; i >=0 ;i--)//反向遍历一遍 
            {
                if ((ratings[i] > ratings[i + 1]) && candyvec[i] < (candyvec[i + 1] + 1))candyvec[i] = candyvec[i + 1] + 1;
                sum += candyvec[i];
            }
             
            return sum;
        }

    参考:

    https://leetcode.com/problems/candy/?tab=Solutions

  • 相关阅读:
    mysql 创建数据库 添加用户 数据库授权给某用户
    Storm近年的发展
    Doris 最佳实践-Compaction调优
    pickle,struct,ujson,orjson 模块
    python用prettytable输出漂亮的表格
    nginx自定义访问日志
    事务 知识点梳理
    14
    13
    8
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6479858.html
Copyright © 2011-2022 走看看