@@ -6,48 +6,31 @@ public class Main {
6
6
7
7
public static class Solution {
8
8
9
- public String getHint (String secret , String guess ) {
10
- HashMap <Character , Set <Integer >> map1 = new HashMap <>();
11
- HashMap <Character , Set <Integer >> map2 = new HashMap <>();
12
- for (int i = 0 ; i < secret .length (); i ++) {
13
- Set <Integer > set = map1 .getOrDefault (secret .charAt (i ), new HashSet <>());
14
- set .add (i );
15
- map1 .put (secret .charAt (i ), set );
16
- }
17
- for (int i = 0 ; i < guess .length (); i ++) {
18
- Set <Integer > set = map2 .getOrDefault (guess .charAt (i ), new HashSet <>());
19
- set .add (i );
20
- map2 .put (guess .charAt (i ), set );
21
- }
22
- int bulls = 0 , cows = 0 ;
23
- for (Character c : map2 .keySet ()) {
24
- Set <Integer > set1 = map1 .get (c );
25
-
26
- if (set1 == null ) {
27
- continue ;
28
- }
29
9
30
- Set <Integer > set2 = map2 .get (c );
10
+ public int candy (int [] ratings ) {
11
+ int [] candys = new int [ratings .length ];
31
12
32
- int count = 0 ;
13
+ Arrays . fill ( candys , 1 ) ;
33
14
34
- for (Integer index : set2 ) {
35
- if (set1 .contains (index )) {
36
- count ++;
37
- }
15
+ for (int i = 1 ; i < ratings .length ; i ++) {
16
+ if (ratings [i ] > ratings [i - 1 ]) {
17
+ candys [i ] = candys [i - 1 ] + 1 ;
38
18
}
39
-
40
- bulls += count ;
41
- cows += Math .min (set1 .size (), set2 .size ()) - count ;
42
19
}
43
-
44
- return String .format ("%dA%dB" , bulls , cows );
20
+ int sum = candys [ratings .length - 1 ];
21
+ for (int i = ratings .length - 2 ; i >= 0 ; i --) {
22
+ if (ratings [i ] > ratings [i + 1 ]) {
23
+ candys [i ] = Math .max (candys [i ], candys [i + 1 ] + 1 );
24
+ }
25
+ sum += candys [i ];
26
+ }
27
+ return sum ;
45
28
}
46
29
}
47
30
48
31
public static void main (String [] args ) {
49
32
Solution solution = new Solution ();
50
- String s = solution .getHint ( "1123" , "0111" );
51
- System .out .println (s );
33
+ System . out . println ( solution .candy ( new int [] { 1 , 3 , 2 , 2 , 1 }) );
34
+ // System.out.println(solution.candy(new int[] {1, 2, 2}) );
52
35
}
53
36
}
0 commit comments