【问题标题】:How is counting the elements in the subarray giving the number of subarrays in the sliding window algorithm如何计算子数组中的元素给出滑动窗口算法中子数组的数量
【发布时间】: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


【解决方案1】:

您应该首先弄清楚 for 循环的不变量是什么。在 for 循环的每次迭代中,它都会修复 right,并找到最左边的 left,使得范围 [left, right] 包含具有最接近但不超过 100 的乘积的元素,对于特定值 @987654323 @。

例如,在上一次迭代中,找到的范围是 [1, 3],具有该范围的子数组是 [5, 2, 6]。请注意,如果我们从左侧开始再包含一个元素,则乘积将等于或超过 100。您可以将其视为找到以 right 结尾的 longest 子数组,该子数组的乘积小于超过 100 个。

假设整数都是正数,那么如果我们知道以right 结尾的最长 子数组满足这个条件,我们也知道任何以right 结尾的较短子数组也将满足这个条件健康)状况。恰好有(right - left) 比我们发现的最长子数组更短。因此,每次我们找到left,我们都会计算(right - left),加上我们找到的最长的。这将是满足条件的以right 结尾的子数组的总数。

由于for 循环检查子数组的每个可能的结束位置(right),并且我们计算了每个结束位置满足条件的所有子数组,因此我们计算了所有满足条件的子数组。

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 2011-03-09
    • 2014-11-05
    • 1970-01-01
    相关资源
    最近更新 更多