-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1248.py
64 lines (56 loc) · 1.57 KB
/
1248.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
'''
1248. Count Number of Nice Subarrays
https://leetcode.com/problems/count-number-of-nice-subarrays/
Given an array of integers nums and an integer k.
A subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
Example 1:
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation:
The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Example 2:
Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There is no odd numbers in the array.
Example 3:
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16
Constraints:
1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length
'''
from typing import *
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
def atMost(numOdd):
numSubArr = left = 0
for idx in range(len(nums)):
numOdd -= nums[idx] % 2
while numOdd < 0:
numOdd += nums[left] % 2
left += 1
numSubArr += idx - left + 1
return numSubArr
return atMost(k) - atMost(k - 1)
#print(Solution().numberOfSubarrays(nums = [1,1,2,1,1], k = 3))
#2
print(Solution().numberOfSubarrays(nums = [2,2,2,1,2,2,1,2,2,2], k = 2))
#16
#2,2,2,1,2,2,1
#2,2,2,1,2,2,1,2
#2,2,2,1,2,2,1,2,2
#2,2,2,1,2,2,1,2,2,2
# 2,2,1,2,2,1,2,2,2
# 2,1,2,2,1,2,2,2
# 1,2,2,1,2,2,2
# 1,2,2,1,2,2
# 1,2,2,1,2
# 1,2,2,1
# 2,1,2,2,1
# 2,1,2,2,1,2
# 2,1,2,2,1,2,2
# 2,2,1,2,2,1
# 2,2,1,2,2,1,2
# 2,2,1,2,2,1,2,2