Candy
来源:互联网 发布:淘宝嘉年华什么意思 编辑:程序博客网 时间:2024/04/27 16:45
题意:给一列学生糖吃,这列学生各有一个rate,rate越大分到的糖就越多,最少分一颗糖;求一列学生至少的分糖总数。
思路:这题和trapping water类似,都需要从左往右和从右往左进行两次遍历,以从左往右为例,定义数组left[],当前的学生和左边的学生相比较,如果rate值是比左边的学生大的话,那就是left[i]+1,否则就置1;
从右往左类似。
代码:
package Candy;public class Candy { public int CandyTest(int []rates){ int []left = new int[rates.length+1]; int []right = new int[rates.length+1]; for(int i = 1 ; i< rates.length ; i++){ if(rates[i] > rates[i-1]) left[i] = left[i-1]+1; else left[i] = 1; } right[rates.length-1] = left[rates.length-1]; for(int i = rates.length - 2; i >= 0 ;i--){ if(rates[i] > rates[i+1]) right[i] = right[i+1]+1; else right[i]=1; } int sum = 0; for(int i = 0 ; i< rates.length ; i++){ sum += Math.max(left[i], right[i]); } return sum; } public static void main(String[] args) { int []rates = {3,2,4,6,5}; Candy cd = new Candy(); System.out.println(cd.CandyTest(rates)); }}
0 0
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- candy
- Candy
- Candy
- Candy
- Candy
- stm8的中断学习1
- 论Web UI自动化测试的不稳定性(二)
- 【Android开发艺术探索】IPC机制(四)-使用AIDL进行跨进程通信
- Linux多线程编程(四)线程同步之信号量
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- Candy
- C#中This用法的简单小例子
- 解决Hibernate:could not initialize proxy - no Session
- 【C语言】.如何求一个整形数组逆序。
- 【英语学习】坚定目标,坚持去做
- nodejs产生图片验证码
- Intel Code Challenge Elimination Round C. Destroying Array
- Servlet的多线程和线程安全
- 构造函数模式