File tree Expand file tree Collapse file tree 1 file changed +75
-7
lines changed
src/main/java/g2001_2100/s2029_stone_game_ix Expand file tree Collapse file tree 1 file changed +75
-7
lines changed Original file line number Diff line number Diff line change 11package g2001_2100 .s2029_stone_game_ix ;
22
33// #Medium #Array #Math #Greedy #Counting #Game_Theory
4- // #2022_05_25_Time_5_ms_(100.00%)_Space_52.9_MB_(78.26 %)
4+ // #2022_05_25_Time_31_ms_(10.87%)_Space_114.5_MB_(65.22 %)
55
66public class Solution {
7+ private int [] stones ;
8+
79 public boolean stoneGameIX (int [] stones ) {
8- int [] cnt = new int [3 ];
9- for (int a : stones ) {
10- cnt [a % 3 ]++;
10+ this .stones = stones ;
11+ int [] freq = new int [3 ];
12+ for (int i : stones ) {
13+ if (i % 3 == 0 ) {
14+ freq [0 ]++;
15+ } else if (i % 3 == 1 ) {
16+ freq [1 ]++;
17+ } else {
18+ freq [2 ]++;
19+ }
20+ }
21+ boolean b1 = false ;
22+ boolean b2 = false ;
23+ int [] a = freq .clone ();
24+ int [] b = freq .clone ();
25+ if (a [1 ] > 0 ) {
26+ a [1 ]--;
27+ b1 = fun (a , 1 );
28+ }
29+ if (b [2 ] > 0 ) {
30+ b [2 ]--;
31+ b2 = fun (b , 2 );
1132 }
12- if (Math .min (cnt [1 ], cnt [2 ]) == 0 ) {
13- return Math .max (cnt [1 ], cnt [2 ]) > 2 && cnt [0 ] % 2 > 0 ;
33+ return b1 || b2 ;
34+ }
35+
36+ private boolean fun (int [] freq , int sum ) {
37+ int n = stones .length ;
38+ int i = 1 ;
39+ while (i < n ) {
40+ if (i % 2 == 0 ) {
41+ if (sum % 3 == 1 ) {
42+ if (freq [0 ] > 0 ) {
43+ freq [0 ]--;
44+ } else if (freq [1 ] > 0 ) {
45+ freq [1 ]--;
46+ sum += 1 ;
47+ } else {
48+ return false ;
49+ }
50+ } else if (sum % 3 == 2 ) {
51+ if (freq [0 ] > 0 ) {
52+ freq [0 ]--;
53+ } else if (freq [2 ] > 0 ) {
54+ freq [2 ]--;
55+ sum += 2 ;
56+ } else {
57+ return false ;
58+ }
59+ }
60+ } else {
61+ if (sum % 3 == 2 ) {
62+ if (freq [0 ] > 0 ) {
63+ freq [0 ]--;
64+ } else if (freq [2 ] > 0 ) {
65+ freq [2 ]--;
66+ sum += 2 ;
67+ } else {
68+ return true ;
69+ }
70+ } else if (sum % 3 == 1 ) {
71+ if (freq [0 ] > 0 ) {
72+ freq [0 ]--;
73+ } else if (freq [1 ] > 0 ) {
74+ freq [1 ]--;
75+ sum += 1 ;
76+ } else {
77+ return true ;
78+ }
79+ }
80+ }
81+ i ++;
1482 }
15- return Math . abs ( cnt [ 1 ] - cnt [ 2 ]) > 2 || cnt [ 0 ] % 2 == 0 ;
83+ return false ;
1684 }
1785}
You can’t perform that action at this time.
0 commit comments