博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode -- Candy
阅读量:5978 次
发布时间:2019-06-20

本文共 1576 字,大约阅读时间需要 5 分钟。

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?

[解题思路]

two pass scan, one pass from left to right, next pass from right to left

when find increment sequence, set candy by k, then increment k

something need to attention, the requirement of this problem is that only children with a higher rating need to get more

candies than their neighors, but if two child has the same rating, we do not need to give more candies

the time complexity is O(n), the space complexity is also O(n)

1 public class Solution { 2     public int candy(int[] ratings) { 3         int N = ratings.length; 4         if(N == 0){ 5             return N; 6         } 7         int[] candy = new int[N]; 8         int sum = N; 9         for(int i = 0, k = 1; i < N; i++){10             if(i - 1 >= 0 && ratings[i] > ratings[i - 1]){11                 candy[i] = Math.max(k ++, candy[i]);12             } else {13                 k = 1;14             }15         }16         17         for(int i = N - 1, k = 1; i >= 0; i--){18             if(i + 1 < N && ratings[i] > ratings[i + 1]){19                 candy[i] = Math.max(k ++, candy[i]);20             } else {21                 k = 1;22             }23         }24         25         for(int i = 0; i < N; i++){26             sum += candy[i];27         }28         return sum;29     }30 }

 

转载地址:http://pwsox.baihongyu.com/

你可能感兴趣的文章
bootstrap-关闭按钮
查看>>
uC/OS-II源码分析(四)
查看>>
percona innobackupex 使用
查看>>
ORA-00257: archiver error. Connect internal only, until freed
查看>>
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type
查看>>
Lync 2013就地升级到Skype for Business 2015-01
查看>>
Mac 系统不兼容移动硬盘无法识别怎么办
查看>>
php 二叉树 与赫夫曼树
查看>>
从产业链看技术的突破,第二届N+ VR&AR&MR技术高峰论坛圆满落幕
查看>>
ZABBIX3.0配置邮件报警
查看>>
马哥运维学习作业(二)
查看>>
php拆分数字字符串方法
查看>>
TCP/IP 某些最常见的错误原因码 (errno)列表
查看>>
spring整合redis缓存
查看>>
Install GPU TensorFlow From Sources w/ Ubuntu 16.04 and Cuda 8.0
查看>>
python线程,进程,协程
查看>>
linux命令:case选择结构语句
查看>>
crontab日志
查看>>
Win32系统下安装Win64补充说明
查看>>
spring boot 传递 List参数
查看>>