leetcode

Alice and Bob Playing Flower Game - Link

Question Description

Alice and Bob have flowers in a garden. Alice has n flowers and Bob has m flowers. They play a game where in each round, they both pick one flower each. If the sum of the number of petals of their flowers is odd, Alice wins. Otherwise, Bob wins.

Return the total number of rounds where Alice wins.


Constraints


Approach

Notice that Alice wins when the sum of petals is odd. Since we don’t know the actual petal counts, we need to think differently.

Consider the parity (even/odd nature) of the flowers:

For any pair (a, b) where a ∈ A and b ∈ B:

So the number of winning rounds for Alice is: (number of odd a) × (number of even b) + (number of even a) × (number of odd b)

This simplifies to: (n/2) × (m - m/2) + (n - n/2) × (m/2) = (n*m)/2

Why this approach works:

Alternative approaches considered:


Dry Run

Example Input: n = 3, m = 2

Step-by-step execution:

Using formula: (3*2)/2 = 3 ✓

Example Input: n = 1, m = 1

Using formula: (1*1)/2 = 0 ✓


Solution

class Solution {
    public long flowerGame(int n, int m) {
        return (long) n * m / 2;
    }
}

Time and Space Complexity