Candy

来源:互联网 发布:淘宝网妈妈斗篷 编辑:程序博客网 时间:2024/04/29 15:18

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一样。

做法:先从左扫描一遍,得到一个每个孩子和其左边孩子对比的结果,如果rating大于左边的,就左边值+1;否则为1

再从右扫一遍,得到孩子和右边孩子的对比结果,同上。同时得到当前孩子必须得到的糖果数:max(左侧扫描结果, 右侧扫描结果)然后加到总结果上。


    public int candy(int[] ratings) {        int n = ratings.length;        int[] c = new int[n];        int[] result = new int[n];        if (n <= 1) {            return n == 0 ? 0 :1;        }                result[0] = 1;        result[n-1] = 1;        for (int i = 1; i < n; i++) {            if (ratings[i] > ratings[i-1]) {                result[i] = result[i-1]+1;            } else {                result[i] = 1;            }        }        int total = result[n-1];        for (int i = n-2; i >= 0; i--) {            int cur;            if (ratings[i] > ratings[i+1]) {                cur = result[i+1]+1;            } else {                cur = 1;            }            total += Math.max(result[i], cur);            result[i] = cur;        }        return total;    }


0 0
原创粉丝点击