Skip to content

Commit

Permalink
Add Subarray Product Less Than K Problem (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
xtenzQ authored Jul 6, 2024
1 parent c201cea commit d5aea5d
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,35 @@ public static int findLongestSubstringAfterOneFlip(String s) {
}
return answer;
}

/**
* Returns the number of subarrays where the product of all the elements in the subarray
* is strictly less than {@code k}.
*
* @param nums the array of positive integers
* @param k the integer threshold
* @return the number of subarrays with product less than {@code k}
* @implNote This method runs in {@code O(n)} time complexity and {@code O(1)} space complexity,
* where {@code n} is the length of {@code nums}.
* @see <a href="https://leetcode.com/problems/subarray-product-less-than-k/">713. Subarray Product Less Than K</a>
*/
public static int numSubarrayProductLessThanK(int[] nums, int k) {
if (k <= 1) {
return 0;
}

int left = 0, count = 1, answer = 0;

for (int right = 0; right < nums.length; right++) {
count *= nums[right];
while (count >= k) {
count /= nums[left];
left++;
}

answer += right - left + 1;
}

return answer;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import static com.xtenzq.arrays.SlidingWindow.findLongestSubstringAfterOneFlip;
import static com.xtenzq.arrays.SlidingWindow.findLongestSubArraySumLessOrEqualK;
import static com.xtenzq.arrays.SlidingWindow.numSubarrayProductLessThanK;
import static org.junit.jupiter.api.Assertions.assertEquals;

class SlidingWindowTest {
Expand Down Expand Up @@ -103,4 +104,39 @@ void testFindLongestSubstringAfterOneFlip_ComplexPattern() {
String s = "100110111001111";
assertEquals(6, findLongestSubstringAfterOneFlip(s));
}

@Test
void testNumSubarrayProductLessThanK_SubarraysWithProductLessThan100() {
int[] nums = {10, 5, 2, 6};
int k = 100;
assertEquals(8, numSubarrayProductLessThanK(nums, k));
}

@Test
void testNumSubarrayProductLessThanK_SubarraysWithProductLessThan0() {
int[] nums = {1, 2, 3};
int k = 0;
assertEquals(0, numSubarrayProductLessThanK(nums, k));
}

@Test
void testNumSubarrayProductLessThanK_SubarraysWithProductLessThan1() {
int[] nums = {1, 2, 3};
int k = 1;
assertEquals(0, numSubarrayProductLessThanK(nums, k));
}

@Test
void testNumSubarrayProductLessThanK_SubarraysWithProductLessThan10() {
int[] nums = {1, 2, 3};
int k = 10;
assertEquals(6, numSubarrayProductLessThanK(nums, k));
}

@Test
void testNumSubarrayProductLessThanK_EmptyArray() {
int[] nums = {};
int k = 100;
assertEquals(0, numSubarrayProductLessThanK(nums, k));
}
}

0 comments on commit d5aea5d

Please sign in to comment.