Count Subarrays With Even Odd Ratio I Problem
#4011
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 4011.
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 <= 10001 <= nums[i] <= 10001 <= a, b <= 1000
Solution
Approach: Enumerate Subarrays
Fix the left end i and extend the right end j, keeping y, the number of odd values in nums[i..j]. The number of even values is then x = j - i + 1 - y.
A subarray is valid when y > 0 and x / y <= a / b. To avoid floating-point error, compare x * b <= y * a instead.
Complexity: time O(n^2), space O(1), where n is the length of nums.
class Solution:
def countRatioSubarrays(self, nums: List[int], a: int, b: int) -> int:
ans = 0
n = len(nums)
for i in range(n):
y = 0
for j in range(i, n):
y += nums[j] % 2
x = j - i + 1 - y
if y and (x / y) <= (a / b):
ans += 1
return ans