leetcode->Candy
来源:互联网 发布:手机剪切视频的软件 编辑:程序博客网 时间:2024/05/21 10:32
<span style="font-family: Arial, Helvetica, sans-serif;">每日一刷,强迫学习</span>
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;
第三步,从右向左扫,遇见当前等级比后一个高,但是糖果数比后一个低,则当前=后一个+1;
代码:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package children;/** * * @author zhaoyufeng */public class Children { public int candy(int[] ratings) { int length = ratings.length; int candySum = 0; int[] candyEach = new int[length]; for (int i = 0; i < length; i++) { candyEach[i] = 1; } for (int i = 1; i < length; i++) { if (ratings[i] > ratings[i - 1]) { candyEach[i] = candyEach[i - 1] + 1; } } for (int i = length - 2; i >= 0; i--) { if (ratings[i] > ratings[i + 1] && candyEach[i] <= candyEach[i + 1] ) { candyEach[i] = candyEach[i + 1] + 1; } } for (int i = 0; i <= length - 1; i++) { System.out.print(" ratings[" + i + "]=" + ratings[i]); } System.out.println(); for (int i = 0; i <= length - 1; i++) { System.out.print(" candyEach[" + i + "]=" + candyEach[i]); candySum += candyEach[i]; } System.out.println(); System.out.println(candySum); return candySum; } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here// int a[] = {1, 2, 2, 4, 2, 1, 45, 3, 23, 2}; int a[] = {1,2,2}; Children child = new Children(); child.candy(a); }}
0 0
- Leetcode: Candy
- LeetCode:Candy
- [leetcode]Candy
- Leetcode: Candy
- 【leetcode】Candy
- LeetCode:Candy
- [LeetCode] Candy
- [LeetCode]Candy
- [LeetCode] Candy
- 【LeetCode】Candy
- LeetCode | Candy
- Leetcode: Candy
- Candy - LeetCode
- leetcode Candy
- LeetCode Candy
- candy leetcode
- Candy -- LeetCode
- [LeetCode] Candy
- 幂次法则power law
- 整数与字符串转换
- LVM的创建与删除
- C++ Primer学习 《语句-Statements》
- Eclipse快捷键 10个最有用的快捷键
- leetcode->Candy
- 程序员生存定律--表达背后的力量(2)【转】
- 把datetime类型的日期转化成年月日或其他格式方法总结
- vim下如何删除空格行和删除行首空格和行尾空格<转>
- spring四种依赖注入方式
- 谁说说抽象类不能被构造的
- Oracle实例恢复(Oracle instance recovery)
- 错误1error C1189: #error : This file requires _WIN32_WINNT to be #defined at least to 0x0403. Value
- cocos2dx 3.x schedule的认识