Alice and Bob Playing Flower Game - Math [JS]

Description 

Solution: Math

Alice wins with an odd number of flowers.
Count all the combinations of creating an odd number.

  • x is odd, y is even.
  • x is even, y is odd.

To find how many even numbers <= nfloor(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 <= nceil(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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]