1
class Solution {
2
public boolean stoneGameIX(int[] stones) {
3
Map<Integer, Integer> div3 = new HashMap<>();
4
div3.put(0, 0);
5
div3.put(1, 0);
6
div3.put(2, 0);
7

8
for (int stone : stones) {
9
div3.put(stone % 3, div3.get(stone % 3) + 1);
10
}
11
// the count of 3's don't matter, only whether it is even or odd
12
div3.put(0, div3.get(0) % 2);
13

14
if (div3.get(1) == 0 && div3.get(2) == 0) {
15
return false;
16
}
17

18
int smaller = Math.min(div3.get(1), div3.get(2));
19
int larger = Math.max(div3.get(2), div3.get(1));
20
// the combinations of 1's and 2's will work with each other in a complementary way.
21
// A pair of 1 and 2 makes modulo 3 to be 0
22
// Three counts of 1 or 2 makes modulo 3 to be 0
23
// so, we need only relative counts
24

25
// if there are even 3's, then bob can't reverse alice's win
26
// so, if all three digits chosen are the same then bob wins, but if there is another option
27
// then alice wins
28
// [1,2,2,2] -> alice picks 1 and wins
29
// [1,3,3,2] -> alice picks 1 or two and wins
30
// [2,2,2] -> alice has to pick the third 2 and loses
31

32
if (div3.get(0) == 0) {
33
return smaller != 0;
34
}
35

36
// all cases now have odd number of 3's, so result can be reversed
37

38
// [1,1,1,1,3] -> 1,1,3,1 picked or 1,3,1,1 picked means alice wins
39
// similar for 2 because the other number doesn't exist to make a %3 pair
40

41
// if the difference of number counts is more than 2 then alice can always force bob
42
// [3,1,2,2,2] ->
43
// [3,1,2,2,2,2] ->
44
if (larger > smaller + 2) {
45
return true;
46
}
47

48
return false;
49
}
50
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0