713. 乘积小于 K 的子数组

摘要
Title: 713. 乘积小于 K 的子数组
Categories: 滑动窗口

Powered by:NEFU AB-IN

Link

713. 乘积小于 K 的子数组

题意

给你一个整数数组 nums 和一个整数 k ,请你返回子数组内所有元素的乘积严格小于 k 的连续子数组的数目。

思路

滑动窗口模板题

  1. 我们需要使用“增量数”,从右向左看,right右移后,窗口新增一个元素,会新增哪些子数组? [1,2,3] -> [1,2,3,4] 窗口内新增一个元素4时,新增的子数组肯定要包含4,以4为右端点,新增的子数组是[4],[3,4],[2,3,4],[1,2,3,4], 一共4个,这个增量就是窗口大小right-left+1。

  2. 在循环外更新,循环外的才是缩减到prod < k的

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 3.8.19 import
import random
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta
from functools import lru_cache
from heapq import heapify, heappop, heappush, nlargest, nsmallest
from itertools import combinations, compress, permutations, starmap, tee
from math import ceil, comb, fabs, floor, gcd, hypot, log, perm, sqrt
from string import ascii_lowercase, ascii_uppercase
from sys import exit, setrecursionlimit, stdin
from typing import Any, Dict, List, Optional, Tuple, TypeVar, Union

# Constants
TYPE = TypeVar('TYPE')
N = int(2e5 + 10)
M = int(20)
INF = int(1e12)
OFFSET = int(100)
MOD = int(1e9 + 7)

# Set recursion limit
setrecursionlimit(int(2e9))


class Arr:
array = staticmethod(lambda x=0, size=N: [x() if callable(x) else x for _ in range(size)])
array2d = staticmethod(lambda x=0, rows=N, cols=M: [Arr.array(x, cols) for _ in range(rows)])
graph = staticmethod(lambda size=N: [[] for _ in range(size)])


class Math:
max = staticmethod(lambda a, b: a if a > b else b)
min = staticmethod(lambda a, b: a if a < b else b)


class IO:
input = staticmethod(lambda: stdin.readline().rstrip("\r\n"))
read = staticmethod(lambda: map(int, IO.input().split()))
read_list = staticmethod(lambda: list(IO.read()))


class Std:
pass

# ————————————————————— Division line ——————————————————————


class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 1:
return 0
prod = 1
l = 0
ans = 0
for r, num in enumerate(nums):
prod *= num
while prod >= k:
prod /= nums[l]
l += 1
ans += r - l + 1
return ans

使用搜索:谷歌必应百度