aboutsummaryrefslogtreecommitdiff
path: root/count_num_nice_subarr.py
diff options
context:
space:
mode:
authorjack <0x6A73@pm.me>2024-06-14 13:13:15 -0600
committerjack <0x6A73@pm.me>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /count_num_nice_subarr.py
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'count_num_nice_subarr.py')
-rw-r--r--count_num_nice_subarr.py34
1 files changed, 34 insertions, 0 deletions
diff --git a/count_num_nice_subarr.py b/count_num_nice_subarr.py
new file mode 100644
index 0000000..de30423
--- /dev/null
+++ b/count_num_nice_subarr.py
@@ -0,0 +1,34 @@
+# 1248. Count Number of Nice Subarrays
+
+"""
+given an array of integers 'nums' and an integers 'k'. a continuous subarray
+is called nice if there are 'k' odd numbers on it. return the number of nice
+subarrays.
+"""
+
+
+class Solution(object):
+ def numberOfSubarrays(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: int
+ """
+ i, cnt, ans = 0, 0, 0
+ for j in range(len(nums)):
+ if nums[j] & 1:
+ k -= 1
+ cnt = 0
+ while k == 0:
+ k += nums[i] & 1
+ i += 1
+ cnt += 1
+ ans += cnt
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.numberOfSubarrays(nums=[1, 1, 2, 1, 1], k=3))
+ print(obj.numberOfSubarrays(nums=[2, 4, 6], k=1))
+ print(obj.numberOfSubarrays(nums=[2, 2, 2, 1, 2, 2, 1, 2, 2, 2], k=2))