-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCandy.java
More file actions
96 lines (80 loc) · 2.73 KB
/
Candy.java
File metadata and controls
96 lines (80 loc) · 2.73 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
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?
*/
//ADD A MUCH BETTER SOLUTION, O(N)
public class Solution {
public int candy(int[] ratings) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (ratings == null) {
return -1;
}
int length = ratings.length;
if (length == 0) {
return 0;
}
int[] leftIteration = new int[length];
int[] rightIteration = new int[length];
leftIteration[0] = 1;
for (int i = 1; i < length; i++) {
if (ratings[i] > ratings[i - 1]) {
leftIteration[i] = leftIteration[i - 1] + 1;
} else {
leftIteration[i] = 1;
}
}
rightIteration[length - 1] = 1;
for (int i = length - 1; i > 0; i--) {
if (ratings[i - 1] > ratings[i]) {
rightIteration[i - 1] = rightIteration[i] + 1;
} else {
rightIteration[i - 1] = 1;
}
}
int sum = 0;
for (int i = 0; i < length; i++) {
sum += Math.max(leftIteration[i], rightIteration[i]);
}
return sum;
}
}
public class Solution {
public int candy(int[] ratings) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (ratings == null) {
return -1;
}
int length = ratings.length;
if (length == 0) {
return 0;
}
int[] candies = new int[length];
candies[0] = 1;
int sum = 1;
for (int i = 1; i < length; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
sum += candies[i];
} else {
//when ratings[i] < ratings[i - 1]
if (candies[i - 1] > 1) {
candies[i] = 1;
} else {
candies[i] = 1;
int k = i;
while (k > 0 && ratings[k] < ratings[k - 1] && candies[k - 1] <= candies[k]) {
candies[k - 1]++;
sum++;
k--;
}
}
}
}
return sum;
}
}