LeetCode Candy

原题链接在这里:https://leetcode.com/problems/candy/

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?

Trapping Rain Water相似。每个孩子能拿到多少糖取决于左右两边,和能储存多少水取决于Math.min(左侧挡板最大值, 右侧挡板最大值)一个道理。

所以先用leftNum保存根据左侧邻居,该孩子能拿到多少糖,若是rating比左侧高,就要比左侧多拿一个,否则只需要拿一个。右侧同理。

最后在走一遍,取左右侧中较大值加入res中。

Time O(n), Space O(n).

AC Java:

 1 public class Solution {
 2     public int candy(int[] ratings) {
 3         if(ratings == null || ratings.length == 0){
 4             return 0;
 5         }
 6         
 7         //get how many candies based on left neighbour
 8         int [] leftNum = new int[ratings.length];
 9         leftNum[0] = 1;
10         for(int i = 1; i<ratings.length; i++){
11             if(ratings[i] > ratings[i-1]){
12                 leftNum[i] = leftNum[i-1]+1;
13             }else{
14                 leftNum[i] = 1;
15             }
16         }
17         
18         //get how many candies base on right neighbour
19         int [] rightNum = new int[ratings.length];
20         rightNum[ratings.length-1] = 1;
21         for(int i = ratings.length-2; i>=0; i--){
22             if(ratings[i] > ratings[i+1]){
23                 rightNum[i] = rightNum[i+1]+1;
24             }else{
25                 rightNum[i] = 1;
26             }
27         }
28         
29         //total number of candies
30         int res = 0;
31         for(int i = 0; i<ratings.length; i++){
32             res += Math.max(leftNum[i], rightNum[i]);
33         }
34         return res;
35     }
36 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4938112.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值