算法系列——Candy
来源:互联网 发布:头脑风暴软件 编辑:程序博客网 时间:2024/06/05 00:35
题目描述
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?
解题思路
贪心算法的运用,双向爬坡。从左到右爬一边,再从右到左爬一边。再累加所有值即可。
程序实现
public class Solution { public int candy(int[] ratings) { int len=ratings.length; int [] candys=new int[len]; //每人先至少分一个 Arrays.fill(candys,1); //从左到右,保证如果右边的ratings值大于左边,candy的也要大些 for(int i=1;i<len;i++){ if(ratings[i]>ratings[i-1]) candys[i]=candys[i-1]+1; } //从右到左,保证如果左边的ratings值大于右边,candy的也要大些 for(int i=len-2;i>=0;i--){ if(ratings[i]>ratings[i+1]&&candys[i]<=candys[i+1]) candys[i]=candys[i+1]+1; } //累加结果 int sum=0; for(int i=0;i<len;i++) sum+=candys[i]; return sum; }}
阅读全文
0 0
- 算法系列——Candy
- LeetCode——Candy
- *candy——leetcode
- LeetCode——Candy
- Leetcode135——Candy
- LeetCode135—Candy
- LeetCode OJ——Candy
- leetcode 135 —— Candy
- 动态规划——candy
- 算法分析与设计丨第七周丨LeetCode(11)——Candy(Hard)
- 135. candy 贪心算法
- 算法系列—贪心算法
- POJ 3372 —— Candy Distribution
- [LeetCode]Candy——分糖果问题
- 第八周——135. Candy
- 2.1.22—线性表—Candy
- [LeetCode]—Candy 分糖果问题
- LeetCode 135. Candy--贪心算法
- Java后台开发面试
- 从一个jsp页面跳转到另一个jsp页面时的参数传递
- ASCII对照表
- SDUT 3893 (山东省第八届ACM省赛A题) Return of the Nim 博弈nim+威佐夫
- volatile
- 算法系列——Candy
- Linux-进程、进程组、作业、会话、控制终端详解
- HDU 3499 Flight(SPFA+map)
- 51nod--1092 回文字符串(非连续!)
- tensorflow学习:使用tensorflow实现word embedding
- cordova device-orientation插件——罗盘
- 职业规划设想
- 【Redis基础】常用命令
- Mister B and Book Reading