|
| 1 | +// Sliding window |
| 2 | +function numSubarrayProductLessThanK(nums, k) { |
| 3 | + if (k <= 1) return 0; |
| 4 | + if (nums.length === 1) return nums[0] < k ? 1 : 0; |
| 5 | + |
| 6 | + let start = 0; |
| 7 | + let count = 0; |
| 8 | + let currentProduct = 1; |
| 9 | + |
| 10 | + for (let i = 0; i < nums.length; i++) { |
| 11 | + const num = nums[i]; |
| 12 | + currentProduct = currentProduct * num; |
| 13 | + |
| 14 | + while (currentProduct >= k) { |
| 15 | + // shrink the window |
| 16 | + currentProduct = currentProduct / nums[start]; |
| 17 | + start++; |
| 18 | + } |
| 19 | + |
| 20 | + count += i - start + 1; |
| 21 | + } |
| 22 | + |
| 23 | + return count; |
| 24 | +} |
| 25 | + |
| 26 | +console.log(numSubarrayProductLessThanK([10, 5, 2, 6], 100)); |
| 27 | +console.log(numSubarrayProductLessThanK([4, 12, 6, 7, 60], 60)); |
| 28 | +console.log(numSubarrayProductLessThanK([4, 12, 60, 7, 6], 60)); |
| 29 | +console.log(numSubarrayProductLessThanKV2([10, 2, 2, 5, 4, 4, 4, 3, 7, 7], 289)); |
| 30 | +console.log(numSubarrayProductLessThanK([1, 2, 3], 0)); |
| 31 | +console.log(numSubarrayProductLessThanK([1, 1, 1], 1)); |
| 32 | +console.log(numSubarrayProductLessThanK([5], 10)); |
| 33 | +console.log(numSubarrayProductLessThanK([4], 2)); |
| 34 | +console.log(numSubarrayProductLessThanK([4, 2], 2)); |
| 35 | + |
| 36 | +// Brute force |
| 37 | +function numSubarrayProductLessThanKV2(nums, k) { |
| 38 | + if (k === 0) return 0; |
| 39 | + if (nums.length === 1) return nums[0] < k ? 1 : 0; |
| 40 | + |
| 41 | + let count = 0; |
| 42 | + |
| 43 | + for (let i = 0; i < nums.length; i++) { |
| 44 | + let product = 1; |
| 45 | + |
| 46 | + for (let j = i; j < nums.length; j++) { |
| 47 | + product = product * nums[j]; |
| 48 | + if (product < k) count++; |
| 49 | + else break; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return count; |
| 54 | +} |
| 55 | + |
| 56 | +console.log('---------'); |
| 57 | +console.log(numSubarrayProductLessThanKV2([10, 5, 2, 6], 100)); |
| 58 | +console.log(numSubarrayProductLessThanKV2([4, 12, 6, 7, 60], 60)); |
| 59 | +console.log(numSubarrayProductLessThanKV2([4, 12, 60, 7, 6], 60)); |
| 60 | +console.log(numSubarrayProductLessThanKV2([10, 2, 2, 5, 4, 4, 4, 3, 7, 7], 289)); |
| 61 | +console.log(numSubarrayProductLessThanKV2([1, 2, 3], 0)); |
| 62 | +console.log(numSubarrayProductLessThanKV2([5], 10)); |
| 63 | +console.log(numSubarrayProductLessThanKV2([4], 2)); |
| 64 | +console.log(numSubarrayProductLessThanKV2([4, 2], 2)); |
0 commit comments