LeetCode | 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?

分析1

可以先从左向右遍历一遍,保证如果右边小孩的rating大于左边邻居小孩,那么右边小孩的糖果也会多一个。

再从右向左遍历一遍,保证如果左边小孩的rating大于右边邻居小孩,那么左边小孩的糖果要更大(多一个或本来就比右边小孩大)。

通过两轮遍历,保证了每个孩子的糖果数和邻居相比都符合题目要求。

这种做法的时间复杂度O(N),空间复杂度O(N)。

解法1

public class Candy {
	public int candy(int[] ratings) {
		if (ratings == null || ratings.length <= 0) {
			return 0;
		}

		int ret = 0;
		int N = ratings.length;
		int[] candy = new int[N];
		candy[0] = 1;
		for (int i = 1; i < N; ++i) {
			candy[i] = 1;
			if (ratings[i] > ratings[i - 1]) {
				candy[i] = candy[i - 1] + 1;
			}
		}
		ret = candy[N - 1];
		for (int i = N - 2; i >= 0; --i) {
			if (ratings[i] > ratings[i + 1]) {
				candy[i] = Math.max(candy[i], candy[i + 1] + 1);
			}
			ret += candy[i];
		}
		return ret;
	}
}
分析2

还有一种只需要遍历一轮,并且空间复杂度O(1)的解法。

在遍历过程中,通过纪录每个递减序列的大小和该序列中的最大糖果数,来不断更新总的糖果数。

具体解释可以看http://oj.leetcode.com/discuss/76/does-anyone-have-a-better-idea这个链接中的best answer。

解法2

public class Candy {
	public int candy(int[] ratings) {
		if (ratings == null || ratings.length <= 0) {
			return 0;
		}

		int ret = 1;
		int seqLen = 0;
		int preCandyCount = 1;
		int maxCountInSeq = preCandyCount;
		for (int i = 1; i < ratings.length; ++i) {
			if (ratings[i] < ratings[i - 1]) {
				++seqLen;
				if (maxCountInSeq == seqLen) {
					++seqLen;
				}
				ret += seqLen;
				preCandyCount = 1;
			} else {
				if (ratings[i] > ratings[i - 1]) {
					++preCandyCount;
				} else {
					preCandyCount = 1;
				}
				ret += preCandyCount;
				seqLen = 0;
				maxCountInSeq = preCandyCount;
			}
		}
		return ret;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值