Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd3aa77c

Browse files
author
applewjg
committed
Candy
1 parent05818e9 commitd3aa77c

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

‎Candy.java

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 12, 2014
4+
Problem: Candy
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/candy/
7+
Notes:
8+
There are N children standing in a line. Each child is assigned a rating value.
9+
You are giving candies to these children subjected to the following requirements:
10+
- Each child must have at least one candy.
11+
- Children with a higher rating get more candies than their neighbors.
12+
What is the minimum candies you must give?
13+
14+
Solution: You may refer to https://github.com/AnnieKim/ITint5/blob/master/031_%E5%88%86%E9%85%8D%E7%B3%96%E6%9E%9C.cpp
15+
1. O(n) space.
16+
2. traverse only once with O(1) space.
17+
*/
18+
19+
publicclassSolution {
20+
publicintcandy(int[]ratings) {
21+
returncandy_1(ratings);
22+
}
23+
publicintcandy_1(int[]ratings) {
24+
intN =ratings.length;
25+
if (N ==0)return0;
26+
int[]height =newint[N];
27+
intres =0;
28+
height[0] =1;
29+
for (inti =1;i <N; ++i) {
30+
height[i] =1;
31+
if (ratings[i] >ratings[i -1]) {
32+
height[i] =height[i -1] +1;
33+
}
34+
}
35+
for (inti =N -2;i >=0; --i) {
36+
if (ratings[i] >ratings[i +1]) {
37+
height[i] =Math.max(height[i],height[i +1] +1);
38+
}
39+
}
40+
for (inti =0;i <N; ++i) {
41+
res +=height[i];
42+
}
43+
returnres;
44+
}
45+
publicintcandy_2(int[]ratings) {
46+
intN =ratings.length;
47+
if (N ==0)return0;
48+
intcandy =1,res =1;
49+
intmaxVal =1,maxIdx =0;
50+
for (inti =1;i <N; ++i) {
51+
if (ratings[i] >=ratings[i -1]) {
52+
candy =ratings[i] ==ratings[i -1] ?1 :candy +1;
53+
maxVal =candy;
54+
maxIdx =i;
55+
}else {
56+
if (candy ==1) {
57+
if (maxVal <=i -maxIdx) {
58+
++maxVal;
59+
++res;
60+
}
61+
res +=i -maxIdx -1;
62+
}
63+
candy =1;
64+
}
65+
res +=candy;
66+
}
67+
returnres;
68+
}
69+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp