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 continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
public int numberOfSubarrays(int[] nums, int k) { return subarray(nums, k) - subarray(nums, k-1); } public int subarray(int[] nums, int k) { int res = 0; int left = 0; int count = 0; for(int right = 0; right < nums.length; right++) { k -= nums[right] % 2; while (k < 0) { k += nums[left] % 2; left++; } res += right - left + 1; } return res; }
浙公网安备 33010602011771号