1248. Count Number of Nice Subarrays
https://leetcode.com/contest/weekly-contest-161/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:
Example 2:
Example 3:
Constraints:
1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length
问刚好有K个奇数的子数组个数。问题围绕子数组和K,动态窗口或DP。用c记录下窗口内奇数的个数,当窗口内奇数个数等于K时前移l直到c再次小于K。前移时[l, r - 1]就是符合条件的一个子数组,增加res,但只增加1的话,对于22212122这样的数组后面两个2和前面的2221能各组成四个新子数组就丢失了。因此再额外用t记录下对于当前l窗口移动了几个格,之后的r扩展时只要不是奇数(会触发l新前移),res就增加t。
Previous424. Longest Repeating Character ReplacementNext340. Longest Substring with At Most K Distinct Characters
Last updated
Was this helpful?