Java O(n) simple mathematical solution explained
Using examples to generalize and understand the best path is the best way to reach this solution.\nTime complexity is O(n) and space complexity is O(1).\n\nclas
Using examples to generalize and understand the best path is the best way to reach this solution.\nTime complexity is O(n) and space complexity is O(1).\n```\nclass Solution {\n    public boolean stoneGameIX(int[] stones) {\n        Map<Integer, Integer> div3 = new HashMap<>();\n        div3.put(0, 0);\n        div3.put(1, 0);\n        div3.put(2, 0);\n        \n        for(int stone : stones){\n            div3.put(stone%3, div3.get(stone%3)+1);\n        }\n\t\t// the count of 3\'s don\'t matter, only whether it is even or odd\n        div3.put(0, div3.get(0)%2);\n        \n        \n        if(div3.get(1) == 0 && div3.get(2) == 0){\n            return false;\n        }\n        \n        int smaller = Math.min(div3.get(1), div3.get(2));\n        int larger = Math.max(div3.get(2), div3.get(1));\n\t\t// the combinations of 1\'s and 2\'s will work with each other in a complementary way. \n\t\t// A pair of 1 and 2 makes modulo 3 to be 0\n\t\t// Three counts of 1 or 2 makes modulo 3 to be 0\n\t\t// so, we need only relative counts\n        \n        // if there are even 3\'s, then bob can\'t reverse alice\'s win\n        // so, if all three digits chosen are the same then bob wins, but if there is another option then alice wins\n        // [1,2,2,2] -> alice picks 1 and wins\n        // [1,3,3,2] -> alice picks 1 or two and wins\n        // [2,2,2] -> alice has to pick the third 2 and loses\n\n        if(div3.get(0) == 0){\n            return smaller != 0;\n        }\n        \n        // all cases now have odd number of 3\'s, so result can be reversed\n        \n        // [1,1,1,1,3] -> 1,1,3,1 picked or 1,3,1,1 picked means alice wins\n        // similar for 2 because the other number doesn\'t exist to make a %3 pair\n        \n        // if the difference of number counts is more than 2 then alice can always force bob\n        // [3,1,2,2,2] -> \n\t\t// [3,1,2,2,2,2] ->\n        if(larger > smaller + 2){\n            return true;\n        }\n        \n        return false;\n    }\n}\n```\n\n**Please upvote if you likes the solution.**
['Java']