Skip to content

Commit f8974c9

Browse files
authored
Create 135. Candy
1 parent 9c3feb3 commit f8974c9

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

135. Candy

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
class Solution {
2+
public int candy(int[] ratings) {
3+
int candies = 0, n = ratings.length;
4+
int[] left = new int[n];
5+
int[] right = new int[n];
6+
7+
Arrays.fill(left, 1);
8+
Arrays.fill(right, 1);
9+
10+
//Left relative array
11+
for(int i = 1; i < n; i++) {
12+
//If current index rating > previous ; give extra candies
13+
if(ratings[i] > ratings[i-1]) left[i] = left[i-1] + 1;
14+
}
15+
16+
//Right relative array
17+
for(int i = n-2; i >= 0; i--) {
18+
if(ratings[i] > ratings[i+1]) right[i] = right[i+1] +1;
19+
}
20+
21+
//Merge both the sides
22+
for(int i = 0; i < n; i++) {
23+
candies = candies + Math.max(left[i], right[i]);
24+
}
25+
26+
return candies;
27+
}
28+
}
29+
30+
31+
class Solution {
32+
public int candy(int[] ratings) {
33+
int[] candies = new int[ratings.length];
34+
Arrays.fill(candies, 1);
35+
36+
for(int i = 1; i < ratings.length; i++) {
37+
if(ratings[i] > ratings[i - 1])
38+
candies[i] = candies[i - 1] + 1;
39+
}
40+
for(int i = ratings.length - 2; i >= 0; i--) {
41+
if(ratings[i] > ratings[i + 1])
42+
candies[i] = Math.max(candies[i], candies[i+1] +1);
43+
}
44+
int total = 0;
45+
for(int candy : candies)
46+
total+=candy;
47+
48+
return total;
49+
}
50+
}
51+
52+
class Solution {
53+
public int candy(int[] ratings) {
54+
if(ratings.length <= 1) return ratings.length;
55+
int candies = 0;
56+
int up = 0, down = 0;
57+
int prevSlope = 0;
58+
59+
for(int i = 1; i < ratings.length; i++) {
60+
//If increasing then 1; if decreasing then -1; if equal then 0.
61+
int currSlope = (ratings[i] > ratings[i-1]) ? 1
62+
: (ratings[i] < ratings[i-1] ? -1 : 0);
63+
// _
64+
//If mountain is changing. \_ || \/ || /
65+
if((prevSlope < 0 && currSlope >= 0) || (prevSlope > 0 && currSlope == 0)) {
66+
candies = candies + sum(up) + sum(down) + (Math.max(up, down));
67+
System.out.println(up + " "+ down + " " +candies);
68+
up = 0;
69+
down = 0;
70+
}
71+
72+
//Add in up/down if slope is increasing or decreasing respectively.
73+
//If it is a plain, add a candy as it is the base case.
74+
if(currSlope > 0) {
75+
up++;
76+
}
77+
else if(currSlope < 0) {
78+
down++;
79+
}
80+
else {
81+
candies++;
82+
}
83+
84+
prevSlope = currSlope;
85+
}
86+
System.out.println(up + " "+ down + " "+ candies);
87+
candies = candies + sum(up) + sum(down) + (Math.max(up, down) + 1);
88+
return candies;
89+
}
90+
91+
int sum(int n) {
92+
return (n * (n + 1)) / 2;
93+
}
94+
}

0 commit comments

Comments
 (0)