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
相关推荐
Java成神之路-几秒前
【算法刷题笔记】全题型导航目录
笔记·算法
爱写代码的倒霉蛋2 分钟前
2022年天梯赛L1-8真题解析(哈希+排序)
数据结构·算法
Struggle_97559 分钟前
算法知识-倍增算法
算法
计算机安禾12 分钟前
【计算机网络】第5篇:网桥学习与生成树算法——环路拓扑中的路径收敛问题
学习·计算机网络·算法
fie888915 分钟前
基于遗传算法的机械故障诊断MATLAB程序
算法·机器学习·matlab
nlpming20 分钟前
opencode MCP(Model Context Protocol)配置手册
算法
MATLAB代码顾问32 分钟前
MATLAB实现灰狼算法优化PID参数
算法·机器学习·matlab
承渊政道2 小时前
【动态规划算法】(完全背包问题从状态定义到空间优化)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
超级大福宝2 小时前
【力扣48. 旋转图像】超好记忆版 + 口诀
c++·算法·leetcode