Skip to content

Commit f944cea

Browse files
committed
refactor: solution 135. Candy
1 parent 011c577 commit f944cea

File tree

2 files changed

+26
-18
lines changed

2 files changed

+26
-18
lines changed

solutions/135. Candy/README.md

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -59,17 +59,21 @@ The third child gets 1 candy because it satisfies the above two conditions.
5959
*/
6060
const candy = function (ratings) {
6161
const n = ratings.length;
62-
const candies = new Array(n).fill(1);
62+
const allocates = Array.from({ length: n }, () => 1);
6363

64-
for (let index = 0; index < n - 1; index++) {
65-
if (ratings[index + 1] <= ratings[index]) continue;
66-
candies[index + 1] = candies[index] + 1;
64+
for (let index = 1; index < n; index++) {
65+
if (ratings[index] > ratings[index - 1]) {
66+
allocates[index] = allocates[index - 1] + 1;
67+
}
6768
}
68-
for (let index = n - 1; index > 0; index--) {
69-
if (ratings[index - 1] <= ratings[index]) continue;
70-
if (candies[index - 1] > candies[index]) continue;
71-
candies[index - 1] = candies[index] + 1;
69+
70+
for (let index = n - 2; index >= 0; index--) {
71+
if (ratings[index] <= ratings[index + 1]) continue;
72+
if (allocates[index] > allocates[index + 1]) continue;
73+
74+
allocates[index] = allocates[index + 1] + 1;
7275
}
73-
return candies.reduce((result, count) => result + count);
76+
77+
return allocates.reduce((result, allocate) => result + allocate);
7478
};
7579
```

solutions/135. Candy/solution.js

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,20 @@
44
*/
55
const candy = function (ratings) {
66
const n = ratings.length;
7-
const candies = new Array(n).fill(1);
7+
const allocates = Array.from({ length: n }, () => 1);
88

9-
for (let index = 0; index < n - 1; index++) {
10-
if (ratings[index + 1] <= ratings[index]) continue;
11-
candies[index + 1] = candies[index] + 1;
9+
for (let index = 1; index < n; index++) {
10+
if (ratings[index] > ratings[index - 1]) {
11+
allocates[index] = allocates[index - 1] + 1;
12+
}
1213
}
13-
for (let index = n - 1; index > 0; index--) {
14-
if (ratings[index - 1] <= ratings[index]) continue;
15-
if (candies[index - 1] > candies[index]) continue;
16-
candies[index - 1] = candies[index] + 1;
14+
15+
for (let index = n - 2; index >= 0; index--) {
16+
if (ratings[index] <= ratings[index + 1]) continue;
17+
if (allocates[index] > allocates[index + 1]) continue;
18+
19+
allocates[index] = allocates[index + 1] + 1;
1720
}
18-
return candies.reduce((result, count) => result + count);
21+
22+
return allocates.reduce((result, allocate) => result + allocate);
1923
};

0 commit comments

Comments
 (0)