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?

    思路:

    每个孩子默认分一颗糖;先从左往右扫,如果右边大于左边,但糖数小于等于左边,则右边的糖数是左边的加一;再从右往左扫,如果左边大于右边,但糖数小于等于右边,左边的糖数是右边的加一。最后求和。

    代码:

     1     int candy(vector<int> &ratings) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         int num = ratings.size();
     5         int result = 0;
     6         vector<int> candies(num, 1);
     7         for(int i = 1; i < num; i++){
     8             if(ratings[i] > ratings[i-1] && candies[i] <= candies[i-1])
     9                 candies[i] = candies[i-1]+1;
    10         }
    11         for(int i = num-2; i >= 0; i--){
    12             if(ratings[i] > ratings[i+1] && candies[i] <= candies[i+1])
    13                 candies[i] = candies[i+1]+1;
    14         }
    15         for(int i = 0; i < num; i++)
    16             result += candies[i];
    17         return result;
    18     }
  • 相关阅读:
    【转】FIddler+Proxifer工具对windows PC客户端进行抓包
    Json提取器(Json Extractor)
    Json断言
    015-Zabbix自动发现和自动注册
    014-Zabbix的自动发现
    013-zabbix trapper方式监控
    012-zabbix主动模式
    011-通过安装percona插件监控MySQL
    010-监控windows主机
    009-通过jmx监控tomcat
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3444417.html
Copyright © 2011-2022 走看看