LeetCode //C - 1248. Count Number of Nice Subarrays

1248. 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.

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 are 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 <= numsi <= 10^5
  • 1 <= k <= nums.length

From: LeetCode

Link: 1248. Count Number of Nice Subarrays


Solution:

Ideas:

count subarrays with exactly k odds = subarrays with at most k odds − subarrays with at most k-1 odds.

Code:
c 复制代码
int atMostKOdds(int* nums, int numsSize, int k) {
    if (k < 0) return 0;

    int left = 0;
    int countOdd = 0;
    int ans = 0;

    for (int right = 0; right < numsSize; right++) {
        if (nums[right] % 2 == 1) {
            countOdd++;
        }

        while (countOdd > k) {
            if (nums[left] % 2 == 1) {
                countOdd--;
            }
            left++;
        }

        ans += right - left + 1;
    }

    return ans;
}

int numberOfSubarrays(int* nums, int numsSize, int k) {
    return atMostKOdds(nums, numsSize, k) - atMostKOdds(nums, numsSize, k - 1);
}
相关推荐
严肃小白兔7 小时前
第 06/24 期:神经网络的反向传播算法:从链式法则到梯度计算
人工智能·神经网络·算法
落羽的落羽7 小时前
【C++】C++17的主要特性
linux·服务器·开发语言·c++·算法·机器学习
文丑颜不良啊8 小时前
LeetCode2841~2860题目解析
java·leetcode
【心态好不摆烂】8 小时前
数据结构基础精讲3
数据结构·算法
漂流瓶jz9 小时前
UVA-1613 K度图的着色 题解答案代码 算法竞赛入门经典第二版
算法·深度优先·图论·贪心·aoapc·算法竞赛入门经典·uva
文丑颜不良啊9 小时前
LeetCode2921~2940题目解析
java·leetcode
Pniubi10 小时前
动态规划入门 ( - 力扣509斐波那契数)
算法·动态规划
吴长建先生重名了11 小时前
GitHub Actions部署报表系统踩坑记:幂等性与限
算法
贝壳69011 小时前
一个2026年2月才上传的库,凭什么敢碰2009年就有人写烂的题目
算法