Java O(1) solution


  • 5

    There's a total only six possible answers:
    1, 2, 3, 4, 7 and 8

    public int flipLights(int n, int m) {
                if (n == 1 && m > 0) {
                    return 2;
                } else if (n == 2 && m == 1) {
                    return 3;
                } else if ((n > 2 && m == 1) || (n == 2 && m > 1)) {
                    return 4;
                } else if (n > 2 && m == 2) {
                    return 7;
                } else if (n > 2 && m > 2) {
                    return 8;
                } else {
                    return 1;
                }
            }
    

    One can imagine there's a 2d array dp with m rows and n columns, suppose m == 5 and n == 7, this dp matrix will be like the following:

    2, 3, 4, 4, 4, 4, 4, 
    2, 4, 7, 7, 7, 7, 7, 
    2, 4, 8, 8, 8, 8, 8, 
    2, 4, 8, 8, 8, 8, 8, 
    2, 4, 8, 8, 8, 8, 8,
    

    As m and n extend, the result will be fixed, so a total only 6 possible answers, we could basically "hardcode" them as the above.

    Also viewable here on Github.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.