当前位置: 首页 > 工具软件 > Candy > 使用案例 >

算法系列——分发糖果(Candy)

苏麒
2023-12-01

题目描述

题目链接: https://leetcode-cn.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?

解题思路

贪心算法的运用,双向爬坡。从左到右爬一边,再从右到左爬一边。再累加所有值即可。

程序实现

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;
    }
}

 类似资料: