Skip to content

Commit dfc70a9

Browse files
refactor 135
1 parent 6d17725 commit dfc70a9

File tree

1 file changed

+23
-20
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+23
-20
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package com.fishercoder.solutions;
22

33
/**
4-
* There are N children standing in a line. Each child is assigned a rating value.
4+
* 135. Candy
5+
6+
There are N children standing in a line. Each child is assigned a rating value.
57
68
You are giving candies to these children subjected to the following requirements:
79
@@ -11,30 +13,31 @@
1113
*/
1214
public class _135 {
1315

16+
public static class Solution1 {
1417
public int candy(int[] ratings) {
15-
int[] candy = new int[ratings.length];
16-
for (int i = 0; i < ratings.length; i++) {
17-
candy[i] = 1;
18+
int[] candy = new int[ratings.length];
19+
for (int i = 0; i < ratings.length; i++) {
20+
candy[i] = 1;
21+
}
22+
23+
for (int i = 0; i < ratings.length - 1; i++) {
24+
if (ratings[i] < ratings[i + 1]) {
25+
candy[i + 1] = candy[i] + 1;
1826
}
27+
}
1928

20-
for (int i = 0; i < ratings.length - 1; i++) {
21-
if (ratings[i] < ratings[i + 1]) {
22-
candy[i + 1] = candy[i] + 1;
23-
}
29+
for (int i = ratings.length - 1; i > 0; i--) {
30+
if (ratings[i] < ratings[i - 1]) {
31+
candy[i - 1] = Math.max(candy[i - 1], candy[i] + 1);
2432
}
33+
}
2534

26-
for (int i = ratings.length - 1; i > 0; i--) {
27-
if (ratings[i] < ratings[i - 1]) {
28-
candy[i - 1] = Math.max(candy[i - 1], candy[i] + 1);
29-
}
30-
}
35+
int sum = 0;
36+
for (int i : candy) {
37+
sum += i;
38+
}
3139

32-
int sum = 0;
33-
for (int i : candy) {
34-
sum += i;
35-
}
36-
37-
return sum;
40+
return sum;
3841
}
39-
42+
}
4043
}

0 commit comments

Comments
 (0)