【发布时间】:2021-12-02 17:19:39
【问题描述】:
考虑以下问题:-
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.
示例:
Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
使用滑动窗口的方法解决这个问题是:-
public class Main {
public static void main(String[] args) {
int arr[] = {10, 5,2, 6};
int k = 100;
int prod = 1, ans = 0, left = 0;
for (int right = 0; right < arr.length; right++) {
prod *= arr[right];
while (prod >= k) prod /= arr[left++];
ans += right - left + 1;
}
System.out.println(ans);
}
}
这是我的问题:-
right - left -1 给出了提取的子数组中的元素总数,那么这如何正确计算可能的子数组总数?
即:对于数组[10, 5, 2, 6]
right=0; left=0; (right-left+1)=1; list=[10]
right=1; left=0; (right-left+1)=2; list=[10, 5]
right=2; left=1; (right-left+1)=2; list=[5, 2]
right=3; left=1; (right-left+1)=3; list=[5, 2, 6]
在遍历数组时计算子数组中元素个数的逻辑是什么,会得到乘积小于K的子数组总数?
【问题讨论】:
-
对于
right=3,你的意思是写[5, 2, 6]吗? -
@Sweeper 是的,编辑了输出以便更好地理解。
-
我认为这仅在数字为正时才有效。您可能希望将其添加为问题的假设。
标签: java algorithm sliding-window