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?

    分析:分糖果。每个小孩必须有一个糖果,ratings值大的孩子比他的邻居分得的糖果数要多。

    自己在纸上画一画,从两边开始分别扫描,分段进行糖果分发。

    从左边开始,假设可以找到x个连续递增的区间;从右边开始,假设可以找到y个连续递增的区间,那么答案就是x + y个区间糖果数量累加的结果。

    用时:37ms

     1 class Solution {
     2 public:
     3     int candy(vector<int>& ratings) {
     4         vector<int> record(ratings.size(), 1);
     5         
     6         for(int i = 1, increase = 1; i < ratings.size(); i++){
     7             if(ratings[i] > ratings[i - 1]) record[i] = ++increase;
     8             else increase = 1;
     9         }
    10         
    11         for(int j = ratings.size() - 2, increase = 1; j >= 0; j--){
    12             if(ratings[j] > ratings[j + 1]) record[j] = max(++increase, record[j]);
    13             else increase = 1;
    14         }
    15         
    16         int result = 0;
    17         for(int i = 0; i < ratings.size(); i++) result += record[i];
    18         
    19         return result;
    20     }
    21 };
  • 相关阅读:
    UVa-133-救济金发放
    UVa-340-猜数字
    UVa-1584-环状序列
    UVa-1585-得分
    UVa-1586-分子量
    BZOJ-3289: Mato的文件管理(莫队算法+树状数组)
    HDU-2824 The Euler function(欧拉函数)
    2017年10月12日22:27:20
    HDU-4715 Difference Between Primes(线性筛法)
    POJ-1185 炮兵阵地(状态压缩DP)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4508497.html
Copyright © 2011-2022 走看看