zoukankan      html  css  js  c++  java
  • 算法题之Leetcode分糖果

    题目:

    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[] nums = new int[ratings.length];
            for (int i=0; i<ratings.length; i++) {
                nums[i] = 1;
            }
            for (int i=0; i<ratings.length - 1; i++) {
                 if (ratings[i+1] > ratings[i]) {
                        nums[i+1] = nums[i] + 1;
                 }
            }
            
            for (int i=ratings.length - 1; i>0; i--) {
                if (ratings[i-1] > ratings[i]) {
                        nums[i-1] = Math.max(nums[i] + 1, nums[i - 1]);
                }
            }
            
            int res = 0;
            for (int i=0; i<ratings.length; i++) {
                 res += nums[i];
            }
            
            return res;
        }
    }
    

      

  • 相关阅读:
    随便练习的进制转换
    回顾快速排序
    常用c++函数
    POJ 1163 The Triangle
    HDU 1155 Bungee Jumping
    ZOJ 3861 Valid Pattern Lock
    POJ 1273 Drainage Ditches
    Hrbust 2240 土豪的时代
    POJ 3468 A Simple Problem with Integers
    POJ 1061 青蛙的约会
  • 原文地址:https://www.cnblogs.com/shixiangwan/p/6734426.html
Copyright © 2011-2022 走看看