Leetcode: Candy

来源:互联网 发布:重庆seo推广公司 编辑:程序博客网 时间:2024/05/23 11:56

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) {// Note: The Solution object is instantiated only once and is reused by// each test case.int len = ratings.length;if(len == 0)return 0;int minSum = len;// Each child must have at least one candy. Better start this way.// I got bugs when start with minSum = 0int curCandy = 0;int[] candy = new int[ratings.length];for(int i = 1; i < len; i++){if(ratings[i - 1] < ratings[i])++curCandy;elsecurCandy = 0;candy[i] = curCandy;}curCandy = 0;for(int i = len - 2; i >= 0;i--){if(ratings[i] > ratings[i + 1])++curCandy;elsecurCandy = 0;minSum += Math.max(candy[i], curCandy);}minSum += candy[len - 1];return minSum;}}


原创粉丝点击