-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path135.candy.js
84 lines (82 loc) · 2.13 KB
/
135.candy.js
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
/*
* @lc app=leetcode id=135 lang=javascript
*
* [135] Candy
*/
// @lc code=start
/**
* @param {number[]} ratings
* @return {number}
*/
var candy = function (ratings) {
let allSatisfied = false;
let candyCount = ratings.length;
let candies = [];
for (let i = 0; i < candyCount; i++) {
candies.push(1);
}
let leftRating, rightRating, leftCandy, rightCandy, myRating, myCandy;
while (!allSatisfied) {
allSatisfied = true;
for (let i = 0; i < ratings.length; i++) {
myRating = ratings[i];
myCandy = candies[i];
leftRating = ratings[i - 1] || null;
rightRating = ratings[i + 1] || null;
leftCandy = candies[i - 1] || null;
rightCandy = candies[i + 1] || null;
if (i === 0) {
// first element
if (myRating > rightRating) {
//i has higher rating than right neightbor
if (myCandy <= rightCandy) {
//and has less candy
candies[i]++;
candyCount++;
allSatisfied = false;
continue;
}
}
} else if (i === ratings.length - 1) {
//last element
if (myRating > leftRating) {
//i has higher rating than left neighbor
if (myCandy <= leftCandy) {
//and has less candy
candies[i]++;
candyCount++;
allSatisfied = false;
continue;
}
}
} else {
if (myRating > leftRating) {
//i has higher rating than left neighbor
if (myCandy <= leftCandy) {
//and has less candy
candies[i]++;
candyCount++;
allSatisfied = false;
continue;
}
}
if (myRating > rightRating) {
//i has higher rating than right neightbor
if (myCandy <= rightCandy) {
//and has less candy
candies[i]++;
candyCount++;
allSatisfied = false;
continue;
}
}
}
}
}
return candyCount;
};
//[1,3,2,2,1]
// @lc code=end
// @after-stub-for-debug-begin
module.exports = candy;
// @after-stub-for-debug-end