713. Subarray Product Less Than K**

本文探讨了LeetCode上一道经典算法题:如何计算一个正整数数组中,所有连续子数组中乘积小于给定值K的子数组数量。通过使用滑动窗口算法,文章详细解析了其高效求解过程,并提供了C++实现代码。

713. Subarray Product Less Than K**

https://leetcode.com/problems/subarray-product-less-than-k/

题目描述

Your are given an array of positive integers nums.

Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.

Example 1:

Input: nums = [10, 5, 2, 6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.

Note:

  • 0 < nums.length <= 50000.
  • 0 < nums[i] < 1000.
  • 0 <= k < 10^6.

C++ 实现 1

使用滑动窗口. 注意两点:

  1. k <= 1 时需要考虑;
  2. 对于 [j, ... i] 范围内的元素, 满足条件的数组个数为 i + 1 - j. 比如 [A, B, C], 如果 j = 0, i = 2, 那么从 C 开始, 只能组成 [C], [B, C], [A, B, C] 三个符合题意的数组, [A, C] 不符合题意, 不连续.
class Solution {
public:
    int numSubarrayProductLessThanK(vector<int>& nums, int k) {
        if (k <= 1) return 0;
        int count = 0, prod = 1, j = 0;
        for (int i = 0; i < nums.size(); ++ i) {
            prod *= nums[i];
            while (prod >= k) prod /= nums[j++];
            count += i - j + 1;
        }
        return count;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值