-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathspltk.go
66 lines (57 loc) · 1021 Bytes
/
spltk.go
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
63
64
65
66
/*
713. Subarray Product Less Than K
https://leetcode.com/problems/subarray-product-less-than-k/
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.
*/
// time: 2018-12-27
package spltk
// sliding window
// time complexity: O(n), where n = len(nums)
// space complexity: O(1)
func numSubArrayProductLessThanK(nums []int, k int) int {
if k <= 1 {
return 0
}
var (
n = len(nums)
l, r int
res int
prod = 1
)
for l < n {
if r < n && prod*nums[r] < k {
prod *= nums[r]
r++
} else if l == r {
l++
r++
} else {
res += r - l
prod /= nums[l]
l++
}
}
return res
}
// 2019-06-16
func numSubArrayProductLessThanK2(nums []int, k int) int {
if k <= 1 {
return 0
}
var (
prod = 1
res = 0
left = 0
)
for right, val := range nums {
prod *= val
for prod >= k {
prod /= nums[left]
left++
}
res += right - left + 1
}
return res
}