Count Subarrays With Even Odd Ratio II Problem
Description
LeetCode Problem 4013.
You are given an integer array nums and two integers a and b.
For a subarray, let:
xbe the number of even elements.ybe the number of odd elements.
The ratio of even to odd elements in a subarray is defined as x / y, where ratios are compared by their exact rational values.
A subarray is considered valid if:
y > 0, andx / y <= a / b.
Return the number of valid subarrays in nums.
Example 1:
Input: nums = [1,2,1,2], a = 3, b = 2
Output: 7
Explanation:
The following are the valid subarrays:
Subarray Values Even Count Odd Count Ratio
nums[0..0] [1] 0 1 0 / 1
nums[0..1] [1, 2] 1 1 1 / 1
nums[0..2] [1, 2, 1] 1 2 1 / 2
nums[0..3] [1, 2, 1, 2] 2 2 2 / 2
nums[1..2] [2, 1] 1 1 1 / 1
nums[2..2] [1] 0 1 0 / 1
nums[2..3] [1, 2] 1 1 1 / 1
Thus, the number of valid subarrays is 7.
Example 2:
Input: nums = [2,2,1], a = 2, b = 1
Output: 3
Explanation:
The following are the valid subarrays:
Subarray Values Even Count Odd Count Ratio
nums[0..2] [2, 2, 1] 2 1 2 / 1
nums[1..2] [2, 1] 1 1 1 / 1
nums[2..2] [1] 0 1 0 / 1
Thus, the number of valid subarrays is 3.
Example 3:
Input: nums = [2,2,2], a = 1, b = 1
Output: 0
Explanation:
Every subarray contains 0 odd numbers, so no subarray is valid.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^91 <= a, b <= 10^9
Solution
Approach: Prefix Sum + Binary Indexed Tree
Let x be the number of even values and y the number of odd values in a subarray. It is valid when y > 0 and x / y <= a / b. Since b > 0 and y > 0, that is the same as a * y - b * x >= 0. When y = 0 the subarray is non-empty, so x > 0 and a * y - b * x < 0: the single inequality already rejects it.
So give every odd value the weight a and every even value the weight -b. We need the number of non-empty subarrays whose weight sum is at least 0.
With prefix sums s, the subarray [L, R - 1] has sum s[R] - s[L], so we count pairs L < R with s[L] <= s[R]. Compress the values of s, sweep R from left to right, ask a Binary Indexed Tree how many earlier prefix sums are at most s[R], add that to the answer, then insert s[R].
Complexity: time O(n log n), space O(n), where n is the length of nums.
from bisect import bisect_left
class BinaryIndexedTree:
__slots__ = "n", "c"
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, delta: int) -> None:
while x <= self.n:
self.c[x] += delta
x += x & -x
def query(self, x: int) -> int:
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def countRatioSubarrays(self, nums: List[int], a: int, b: int) -> int:
n = len(nums)
s = [0] * (n + 1)
for i, x in enumerate(nums):
s[i + 1] = s[i] + (a if x % 2 else -b)
st = sorted(set(s))
bit = BinaryIndexedTree(len(st) + 1)
ans = 0
for v in s:
x = bisect_left(st, v) + 1
ans += bit.query(x)
bit.update(x, 1)
return ans