leetcode713. Subarray Product Less Than K

Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly 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.

Example 2:

Input: nums = [1,2,3], k = 0

Output: 0

思路:使用滑动窗口的思路,找取每一个符合条件的小窗,统计其内部子数组数量。

注意,对于某一个值,我们只关注以它为最右边元素的子数组。这样可以减少重复讨论的麻烦。

python 复制代码
class Solution:
    def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
        if k <= 1: return 0
        left, right, multi, ans = 0, 0, 1, 0
        while right < len(nums):
            multi *= nums[right] # 以右侧元素为pivot
            while multi >= k: # 找到对应这个pivot的最长窗口左侧点
                multi //= nums[left]
                left += 1
            ans += right - left + 1 # 统计以pivot为右侧元素的子数组
            right += 1
        return ans
相关推荐
小王C语言8 分钟前
【线程概念与控制】:线程封装
jvm·c++·算法
kyle~15 分钟前
工程数学---点云配准卡布施(Kabsch)算法(求解最优旋转矩阵)
线性代数·算法·矩阵
张二娃同学29 分钟前
03_变量常量与输入输出_printf与scanf详解
算法
江南十四行1 小时前
并发编程(一)
java·jvm·算法
z200509301 小时前
今日算法(依旧二叉树)
算法·leetcode·职场和发展
Zxc_2 小时前
《遗传算法:从自然选择到Rastrigin函数优化,手写一个完整的进化求解器》
算法
阿Y加油吧2 小时前
两道经典动态规划题:乘积最大子数组 & 分割等和子集 复盘笔记
笔记·算法·动态规划
三品吉他手会点灯2 小时前
C语言学习笔记 - 33.数据类型 - printf函数的详细用法
c语言·开发语言·笔记·学习·算法
NashSKY3 小时前
PnP 问题:数学描述与 DLT 算法推导
算法·矩阵分解·多视图几何·射影几何
csdn_aspnet3 小时前
C++ Lomuto分区算法(Lomuto Partition Algorithm)
开发语言·c++·算法