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);
}
相关推荐
All for pursuit.1 天前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode
释厄6231 天前
BSD 基础论——不要忘记连接·不要停滞循环·AI基础算法
人工智能·算法
iCxhust1 天前
C语言struct结构体实现类定义
c语言·开发语言·单片机·嵌入式硬件·51单片机
yi0111 天前
DAY19: LeetCode 28 找出字符串中第一个匹配项的下标
人工智能·笔记·python·算法·leetcode
不会就选b1 天前
算法日常・每日刷题--<动态规划>6
数据结构·算法·leetcode
释厄6231 天前
AI犯错即异质论——正确认知=免疫与安全防控技术算法
大数据·算法·安全
漂流瓶jz1 天前
UVA-12545 比特变换器 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·题解·aoapc·算法竞赛入门经典·uva·12545
重生之我复员之后重当黄毛1 天前
vscode配置c/c++环境
c语言·前端·visual studio
积流成海1 天前
哈希碰撞攻击全解析:从MD5到SHA1的安全演进史
算法·安全·哈希算法·哈希函数·盘子工具站·哈希计算
shangan_31 天前
C语言学习
c语言·开发语言·学习