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);
}
相关推荐
是隼人1 小时前
buuctf-pwn picoctf_2018_shellcode(ret2shellcode)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
潜创微科技2 小时前
IT6520:USB-C 转 MIPI 高集成控制器,DP 1.4a 转 MIPI 单芯片搞定 4K120 显示
c语言·开发语言·低延迟·掌机·联阳
wzdark2 小时前
多维数组在算法设计中的存储映射问题4
算法
Phil3232 小时前
多智能体不是越多越好:Google《Towards a Science of Scaling Agent Systems》论文深度解读
算法
6Hzlia2 小时前
【Classic 150 刷题计划】 LeetCode 26. 删除有序数组中的重复项 | C++ 快慢双指针经典模板
c++·算法·leetcode
白色的北极熊3 小时前
字符转 ASCII 码
c语言
huang5791473 小时前
基于滑动窗口的流式数据算法优化思路3
算法
Ulyanov3 小时前
AudioVision Pro:基于 PySide6 + sounddevice 的实时音频可视化播放器设计
python·算法·音视频
土司大王3 小时前
LeetCode hot100——74.搜索二维矩阵:Java 二分模板
java·算法·leetcode