Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4d29a81

Browse files
Subarray Product Less Than K
1 parent 030763d commit 4d29a81

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,5 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
3737
- [x] [Squares of a Sorted Array](Two-Pointers/977-Squares-of-a-Sorted-Array.py)
3838
- [x] [Backspace String Compare](Two-Pointers/844-Backspace-String-Compare.py)
3939
- [x] [Find the Duplicate Number](Two-Pointers/287-Find-the-Duplicate-Number.py)
40+
- [x] [Subarray Product Less Than K](Two-Pointers/713-Subarray-Product-Less-Than-K.py)
4041

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"Leetcode- https://leetcode.com/problems/subarray-product-less-than-k/ "
2+
'''
3+
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.
4+
5+
Example 1:
6+
7+
Input: nums = [10,5,2,6], k = 100
8+
Output: 8
9+
Explanation: The 8 subarrays that have product less than 100 are:
10+
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
11+
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
12+
'''
13+
14+
# Solution-1 TLE
15+
def numSubarrayProductLessThanK(self, nums, k):
16+
count = 0
17+
ans = 1
18+
for i in range(0, len(nums)):
19+
if nums[i] < k:
20+
count += 1
21+
ans = nums[i]
22+
for j in range(i+1, len(nums)):
23+
ans = ans*nums[j]
24+
25+
if ans < k:
26+
count += 1
27+
else:
28+
break
29+
return count
30+
31+
# T:O(N^2)
32+
# S:O(1)
33+
34+
# Solution-2
35+
def numSubarrayProductLessThanK(self, nums, k):
36+
if k <= 1:
37+
return 0
38+
prod = 1
39+
cur = left = 0
40+
for right, val in enumerate(nums):
41+
prod *= val
42+
while prod >= k:
43+
prod /= nums[left]
44+
left += 1
45+
cur += right - left + 1
46+
return cur
47+
48+
# T:O(N)
49+
# S:O(1)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /