# 713. Subarray Product Less Than K

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

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

> 内容描述

```
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.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N^2)******- 空间复杂度: O(N)******

跟第560题思路一样，维护一个当前积的常量，每次只要看之前有多少个积大于 cur_product/nums[i]的，如果有就说明最近出现的这个subarray product可以小于k

但是超时了

```
class Solution(object):
    def numSubarrayProductLessThanK(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k == 0:
            n = nums.count(0)
            return n*(n+1)/2
        # 这是为了保证如果当前product的值就等于k的话，我们其实也相当于找到一次
        lookup = {1:1}
        res = 0
        cur_product = 1
        for num in nums:
            cur_product *= num
            res += sum(lookup[key] for key in lookup.keys() if key > cur_product/k)
            # for key in lookup.keys():
            #     if key > cur_product / k:
            #         res += lookup.get(key)
            lookup[cur_product] = lookup.get(cur_product, 0) + 1 
        return res
```

> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

参考[gabbu](https://leetcode.com/problems/subarray-product-less-than-k/discuss/108846/Python-solution-with-detailed-explanation)
```
Initialize start and end to index 0. Initialize prod to 1. Iterate end from 0 to len(nums)-1. 
Now if prod * nums[end] is less than k, then all subarray between start and end contribute to the solution. 
Since we are moving from left to right, we would have already counted all valid subarrays from start to end-1. 
How many new subarrays with nums[end]? Answer: end-start. What will be the updated prod? Answer: prod * nums[end].

```

双指针走起，beats 74.86%

```python
class Solution(object):
    def numSubarrayProductLessThanK(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k <= 1:
            return 0
        start, end, prod, res = 0, 0, 1, 0
        while end < len(nums):
            prod *= nums[end]
            end += 1
            while prod >= k:
                prod /= nums[start]
                start += 1
            res += end - start
        return res
```
