LeetCode-135.Candy

来源:互联网 发布:冷漠的文字软件 编辑:程序博客网 时间:2024/06/05 21:01

https://leetcode.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?

跟题LeetCode-42.Trapping Rain Water 类似,使用两次动态规划

public int Candy(int[] ratings)     {        int n = ratings.Length;        if (n < 2)            return 1;        int[] left = new int[n];        left[0] = 1;        for (int i = 1; i < n; i++)        {            left[i] = 1;            if (ratings[i] > ratings[i - 1])                left[i] += left[i - 1];        }        int[] right = new int[n];        right[n - 1] = left[n - 1];        int res= left[n - 1];         for (int i = n-2; i >=0; i--)        {            right[i] = 1;            if (ratings[i] > ratings[i + 1])                right[i] += right[i + 1];            res += Math.Max(left[i], right[i]);        }        return res;    }

优化减少空间,省去right数组

public int Candy(int[] ratings)     {        int n = ratings.Length;        if (n < 2)            return 1;        int[] left = new int[n];        left[0] = 1;        for (int i = 1; i < n; i++)        {            left[i] = 1;            if (ratings[i] > ratings[i - 1])                left[i] += left[i - 1];        }        int res= left[n - 1],right;         for (int i = n-2; i >=0; i--)        {            right = 1;            if (ratings[i] > ratings[i + 1])                right += left[i + 1];            res += Math.Max(left[i], right);            left[i] = right;        }        return res;    }


参考 http://blog.csdn.net/linhuanmars/article/details/21424783


0 0
原创粉丝点击