Skip to content

3021. Alice and Bob Playing Flower Game

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  long long flowerGame(int n, int m) {
    // Alice wins if x + y is odd, occurring when:
    //   1. x is even and y is odd, or
    //   2. y is even and x is odd.
    const int xEven = n / 2;
    const int yEven = m / 2;
    const int xOdd = (n + 1) / 2;
    const int yOdd = (m + 1) / 2;
    return static_cast<long>(xEven) * yOdd + static_cast<long>(yEven) * xOdd;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public long flowerGame(int n, int m) {
    // Alice wins if x + y is odd, occurring when:
    //   1. x is even and y is odd, or
    //   2. y is even and x is odd.
    final int xEven = n / 2;
    final int yEven = m / 2;
    final int xOdd = (n + 1) / 2;
    final int yOdd = (m + 1) / 2;
    return (long) xEven * yOdd + (long) yEven * xOdd;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def flowerGame(self, n: int, m: int) -> int:
    # Alice wins if x + y is odd, occurring when:
    #   1. x is even and y is odd, or
    #   2. y is even and x is odd.
    xEven = n // 2
    yEven = m // 2
    xOdd = (n + 1) // 2
    yOdd = (m + 1) // 2
    return xEven * yOdd + yEven * xOdd