-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathCandy.java
More file actions
38 lines (31 loc) · 681 Bytes
/
Candy.java
File metadata and controls
38 lines (31 loc) · 681 Bytes
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
class Solution {
// TC : O(n)
// SC: O(n)
public int candy(int[] ratings) {
int totalCandies =0;
int[] distribution =new int[ratings.length];
Arrays.fill(distribution, 1);
for(int i=0;i<ratings.length-1;i++)
{
if(ratings[i+1]>ratings[i])
{
distribution[i+1]= distribution[i]+1;
}
}
for(int i=ratings.length-1;i>0;i--)
{
if(ratings[i-1]>ratings[i])
{
if(distribution[i-1]<=(distribution[i]))
{
distribution[i-1]=distribution[i]+1;
}
}
}
for(int i=0;i<ratings.length;i++)
{
totalCandies+=distribution[i];
}
return totalCandies;
}
}