Skip to content

Commit ff7185b

Browse files
committed
Add solution #135
1 parent a0f30dc commit ff7185b

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium|
8181
133|[Clone Graph](./0133-clone-graph.js)|Medium|
8282
134|[Gas Station](./0134-gas-station.js)|Medium|
83+
135|[Candy](./0135-candy.js)|Hard|
8384
136|[Single Number](./0136-single-number.js)|Easy|
8485
141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy|
8586
142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium|

solutions/0135-candy.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 135. Candy
3+
* https://leetcode.com/problems/candy/
4+
* Difficulty: Hard
5+
*
6+
* There are n children standing in a line. Each child is assigned a rating value given
7+
* in the integer array ratings.
8+
*
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+
*
13+
* Return the minimum number of candies you need to have to distribute the candies to
14+
* the children.
15+
*/
16+
17+
/**
18+
* @param {number[]} ratings
19+
* @return {number}
20+
*/
21+
var candy = function(ratings) {
22+
const data = new Array(ratings.length).fill(1);
23+
24+
for (let i = 1; i < ratings.length; i++) {
25+
if (ratings[i - 1] < ratings[i]) {
26+
data[i] = data[i - 1] + 1;
27+
}
28+
}
29+
30+
for (let i = ratings.length - 1; i > 0; i--) {
31+
if (ratings[i - 1] > ratings[i]) {
32+
data[i - 1] = data[i - 1] > data[i] + 1 ? data[i - 1] : data[i] + 1;
33+
}
34+
}
35+
36+
return data.reduce((sum, n) => sum + n, 0);
37+
};

0 commit comments

Comments
 (0)