|
| 1 | +from typing import List |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + # Gets TLEd. |
| 6 | + def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: |
| 7 | + n = len(nums) |
| 8 | + ans = 0 |
| 9 | + |
| 10 | + for i in range(n): |
| 11 | + prod = 1 |
| 12 | + for j in range(i, n): |
| 13 | + prod *= nums[j] |
| 14 | + if prod < k: |
| 15 | + ans += 1 |
| 16 | + else: |
| 17 | + break |
| 18 | + |
| 19 | + return ans |
| 20 | + |
| 21 | + |
| 22 | +class OfficialSolution: |
| 23 | + def numSubarrayProductLessThanKApproach2(self, nums: List[int], k: int) -> int: |
| 24 | + """ |
| 25 | + == Approach #2: Sliding Window == |
| 26 | + == Intuition == |
| 27 | + For each right, call opt(right) the smallest left so that the product of the |
| 28 | + subarray nums[left] * nums[left+1] * ... * nums[right] is less than k. opt is a |
| 29 | + monotone increasing function, so we can use a sliding window. |
| 30 | +
|
| 31 | + == Algorithm == |
| 32 | + Our loop invariant is that left is the smallest value so that the product in the |
| 33 | + window prod = nums[left] * nums[left+1] * ... * nums[right] is less than k. |
| 34 | + For every right, we update left and prod to maintain this invariant. Then, the |
| 35 | + number of intervals with subarray product less than k and with right-most |
| 36 | + coordinate right, is right - left + 1. We'll count all of these for each value |
| 37 | + of right. |
| 38 | +
|
| 39 | + == Complexity Analysis == |
| 40 | + - Time Complexity: O(N), where N is the length of nums. At each iteration, we |
| 41 | + either increase left or right, and we both left and right can be incremented |
| 42 | + at most N times. |
| 43 | + - Space Complexity: O(1). |
| 44 | + """ |
| 45 | + left = right = 0 |
| 46 | + prod = 1 |
| 47 | + ans = 0 |
| 48 | + |
| 49 | + while right < len(nums): |
| 50 | + # Case 1. Include right. |
| 51 | + if prod * nums[right] < k: |
| 52 | + prod *= nums[right] |
| 53 | + ans += right - left + 1 |
| 54 | + right += 1 |
| 55 | + # Case 2. Cannot include right. |
| 56 | + # Case 2a. If left and right point to same element. |
| 57 | + elif left == right: |
| 58 | + left += 1 |
| 59 | + right += 1 |
| 60 | + # Case 2b. Left points to a left element. |
| 61 | + else: |
| 62 | + prod //= nums[left] |
| 63 | + left += 1 |
| 64 | + |
| 65 | + return ans |
0 commit comments