-
Notifications
You must be signed in to change notification settings - Fork 1
/
135.Candy.cs
40 lines (40 loc) · 1.21 KB
/
135.Candy.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class Solution {
public int Candy(int[] ratings) {
if (ratings.Length == 0) return 0;
var result = 0;
var previousRating = ratings[0];
var previousCandy = 0;
var downCount = 0;
int? downCountThreshold = null;
foreach (var rating in ratings)
{
if (rating == previousRating)
{
result += 1;
previousCandy = 1;
downCount = 1;
downCountThreshold = null;
}
else if (rating > previousRating)
{
++previousCandy;
result += previousCandy;
downCount = 1;
downCountThreshold = null;
}
else
{
if (downCountThreshold == null)
{
downCountThreshold = previousCandy - 1;
}
previousCandy = 1;
result += downCount + (downCount > downCountThreshold.Value ? 1 : 0);
++downCount;
}
previousRating = rating;
//System.Console.WriteLine("{0} {1}", previousCandy, result);
}
return result;
}
}