LeetCode2.1.22 (Candy)
2015-08-22 17:10
387 查看
2.1.22 Candy
描述
ere 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?
两次扫描首先从左到右,然后从右到左,但是后者的判断条件要注意一下
描述
ere 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?
两次扫描首先从左到右,然后从右到左,但是后者的判断条件要注意一下
public static int solution2_1_22(int[] rating){ if(rating.length==1) return 1; else{ int[] candy=new int[rating.length]; candy[0]=1; for(int i=1;i<candy.length;i++){ if (rating[i]>rating[i-1]) candy[i]=candy[i-1]+1; else candy[i]=1; } for(int i=rating.length-2;i>=0;i--){ if((rating[i]>rating[i+1])&&(candy[i]<=candy[i+1]))//注意这里后一半的判断条件不能少 candy[i]=candy[i+1]+1; } int total=0; for(int i=0;i<candy.length;i++){ total+=candy[i]; } return total; } }
相关文章推荐
- xtrabackup与mysqldump对比测试
- js文件制作博客的目录索引2
- 输入10个学生的姓名、学号和成绩,将其中不及格者输出
- 【Nutch】Nutch的抓取流程
- VS2012加载DLL编译出现试图加载格式不正确的程序; 以及运行出现Mixed mode assembly is built against version 'v2.0.50727' of the
- Java实现二叉树的先序、中序、后序、层级遍历
- 动态限制UITextField或UITextView用户输入中英文混编字数统计
- Xml的读取
- 【8-22】java学习笔记04
- 湖南省第八届大学生计算机程序设计竞赛1115: 最短的名字(模拟)
- java性能测试中遇到的奇怪现象
- 湖南省第九届大学生计算机程序设计竞赛1334: 好老师 (模拟)
- 进程和线程之间的通信
- js文件制作博客的目录索引
- 20150820-Linux命令概述及一些基本命令
- vim编辑器简单使用(4)
- Linux信号通讯编程(国嵌总结)
- Events and Delegates(事件和委托)
- LeetCode2.1.21(Gas Station)
- 哈哈