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?

问题分析

这题的大意是有一排孩子,每个孩子有一个评分ratings,给这些孩子分糖,如果这个孩子的评分高于他的邻居,那么他要拿更多的糖。
这是典型的贪心算法问题,每个孩子只要保证若他的评分高,那么他的糖果数要大于他的左右邻居,我们只需要从左往右扫一遍数组处理好左邻居,再从右往左扫一遍处理好右邻居即可

代码实现

public int candy(int[] ratings) {
        int n = ratings.length;
        int[] num = new int[n];
        Arrays.fill(num, 1);//保证每人都有一颗
        for (int i = 1; i < n; i++) {//从左往右扫一遍,保证左邻居颗数维持题意
            if (ratings[i] > ratings[i - 1] && num[i] <= num[i - 1]) {
                num[i] = num[i - 1] + 1;
            }
        }
        for (int i = n - 1; i > 0; i--) {//从右往左扫一遍,保证右邻居颗数维持题意
            if (ratings[i] < ratings[i - 1] && num[i] >= num[i - 1]) {
                num[i - 1] = num[i] + 1;
            }
        }
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum = sum + num[i];
        }
        return sum;
    }

你可能感兴趣的:(LeetCode每日一题:分糖问题)