File tree 1 file changed +23
-20
lines changed
src/main/java/com/fishercoder/solutions
1 file changed +23
-20
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
3
/**
4
- * There are N children standing in a line. Each child is assigned a rating value.
4
+ * 135. Candy
5
+
6
+ There are N children standing in a line. Each child is assigned a rating value.
5
7
6
8
You are giving candies to these children subjected to the following requirements:
7
9
11
13
*/
12
14
public class _135 {
13
15
16
+ public static class Solution1 {
14
17
public int candy (int [] ratings ) {
15
- int [] candy = new int [ratings .length ];
16
- for (int i = 0 ; i < ratings .length ; i ++) {
17
- candy [i ] = 1 ;
18
+ int [] candy = new int [ratings .length ];
19
+ for (int i = 0 ; i < ratings .length ; i ++) {
20
+ candy [i ] = 1 ;
21
+ }
22
+
23
+ for (int i = 0 ; i < ratings .length - 1 ; i ++) {
24
+ if (ratings [i ] < ratings [i + 1 ]) {
25
+ candy [i + 1 ] = candy [i ] + 1 ;
18
26
}
27
+ }
19
28
20
- for (int i = 0 ; i < ratings .length - 1 ; i ++) {
21
- if (ratings [i ] < ratings [i + 1 ]) {
22
- candy [i + 1 ] = candy [i ] + 1 ;
23
- }
29
+ for (int i = ratings .length - 1 ; i > 0 ; i --) {
30
+ if (ratings [i ] < ratings [i - 1 ]) {
31
+ candy [i - 1 ] = Math .max (candy [i - 1 ], candy [i ] + 1 );
24
32
}
33
+ }
25
34
26
- for (int i = ratings .length - 1 ; i > 0 ; i --) {
27
- if (ratings [i ] < ratings [i - 1 ]) {
28
- candy [i - 1 ] = Math .max (candy [i - 1 ], candy [i ] + 1 );
29
- }
30
- }
35
+ int sum = 0 ;
36
+ for (int i : candy ) {
37
+ sum += i ;
38
+ }
31
39
32
- int sum = 0 ;
33
- for (int i : candy ) {
34
- sum += i ;
35
- }
36
-
37
- return sum ;
40
+ return sum ;
38
41
}
39
-
42
+ }
40
43
}
You can’t perform that action at this time.
0 commit comments