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
相关推荐
南玖yy25 分钟前
数据结构C语言练习(栈)
c语言·数据结构·算法
阿镇吃橙子38 分钟前
一些手写及业务场景处理问题汇总
前端·算法·面试
酱酱哥玩AI42 分钟前
Trae编译器:实现多目标班翠鸟优化算法(IPKO)无人机路径规划仿真(Python版),完整代码
算法
MPCTHU1 小时前
二叉树、排序算法与结构图
数据结构·算法·排序算法
亓才孓1 小时前
[leetcode]树的操作
算法·leetcode·职场和发展
王禄DUT1 小时前
化学方程式配平 第33次CCF-CSP计算机软件能力认证
开发语言·c++·算法
wuqingshun3141591 小时前
蓝桥杯 XYZ
数据结构·c++·算法·职场和发展·蓝桥杯
DreamByte1 小时前
C++菜鸟教程 - 从入门到精通 第五节
开发语言·c++·算法
南玖yy2 小时前
数据结构C语言练习(两个队列实现栈)
c语言·数据结构·算法
明朝百晓生2 小时前
【强化学习】【1】【PyTorch】【强化学习简介优化框架】
算法