Alice and Bob Playing Flower Game - Math [JS]
Solution: Math
Alice wins with an odd number of flowers.
Count all the combinations of creating an odd number.
xis odd,yis even.xis even,yis odd.
To find how many even numbers <= n: floor(n / 2)
- e.g.
n = 5->[2,4]->floor(n / 2) = 2 - e.g.
n = 6->[2,4,6]->floor(n / 2) = 3
To find how many odd numbers <= n: ceil(n / 2)
- e.g.
n = 5->[1,3,5]->ceil(n / 2) = 3 - e.g.
n = 6->[1,3,5]->ceil(n / 2) = 3
Time Complexity: O(1)
Space Complexity: O(1)
var flowerGame = function(n, m) {
let oddEven = countOdd(n) * countEven(m);
let evenOdd = countEven(n) * countOdd(m);
return oddEven + evenOdd;
};
function countOdd(x) {
return Math.ceil(x / 2);
}
function countEven(x) {
return Math.floor(x / 2);
}
Comments
Post a Comment