📌  相关文章
📜  总和小于 K 的子数组的数量

📅  最后修改于: 2022-05-13 01:57:47.309000             🧑  作者: Mango

总和小于 K 的子数组的数量

给定一个非负数数组和一个非负数 k,找出总和小于 k 的子数组的数量。我们可以假设没有溢出。
例子 :

Input : arr[] = {2, 5, 6}
        K = 10
Output : 4
The subarrays are {2}, {5}, {6} and
{2, 5},

Input : arr[] = {1, 11, 2, 3, 15}
        K = 10
Output : 4
{1}, {2}, {3} and {2, 3}

一个简单的解决方案是生成数组的所有子数组,然后计算总和小于 K 的数组的数量。
以下是上述方法的实现:

C++
// CPP program to count
// subarrays having sum
// less than k.
#include 
using namespace std;
 
// Function to find number
// of subarrays having sum
// less than k.
int countSubarray(int arr[],
                  int n, int k)
{
    int count = 0;
 
    for (int i = 0; i < n; i++) {
        int sum = 0;
        for (int j = i; j < n; j++) {
 
            // If sum is less than k
            // then update sum and
            // increment count
            if (sum + arr[j] < k) {
                sum = arr[j] + sum;
                count++;
            }
            else {
                break;
            }
        }
    }
 
    return count;
}
 
// Driver Code
int main()
{
    int array[] = { 1, 11, 2, 3, 15 };
    int k = 10;
    int size = sizeof(array) / sizeof(array[0]);
    int count = countSubarray(array, size, k);
    cout << count << "\n";
}


Java
// Java program to count subarrays
// having sum less than k.
import java.io.*;
 
class GFG {
 
    // Function to find number of
    // subarrays having sum less than k.
    static int countSubarray(int arr[],
                             int n, int k)
    {
        int count = 0;
 
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = i; j < n; j++) {
 
                // If sum is less than
                // k then update sum and
                // increment count
                if (sum + arr[j] < k) {
                    sum = arr[j] + sum;
                    count++;
                }
                else {
                    break;
                }
            }
        }
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int array[] = { 1, 11, 2, 3, 15 };
        int k = 10;
        int size = array.length;
        int count = countSubarray(array, size, k);
        System.out.println(count);
    }
}
 
// This code is contributed by Sam007


Python3
# python program to count subarrays
# having sum less than k.
 
# Function to find number of subarrays
# having sum less than k.
def countSubarray(arr, n, k):
    count = 0
 
    for i in range(0, n):
        sum = 0;
        for j in range(i, n):
             
            # If sum is less than k
            # then update sum and
            # increment count
            if (sum + arr[j] < k):
                sum = arr[j] + sum
                count+= 1
            else:
                break
    return count;
 
 
# Driver Code
array = [1, 11, 2, 3, 15]
k = 10
size = len(array)
count = countSubarray(array, size, k);
print(count)
 
# This code is contributed by Sam007


C#
// C# program to count subarrays
// having sum less than k.
using System;
 
class GFG {
 
    // Function to find number
    // of subarrays having sum
    // less than k.
    static int countSubarray(int[] arr,
                             int n, int k)
    {
        int count = 0;
 
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = i; j < n; j++) {
 
                // If sum is less than k
                // then update sum and
                // increment count
                if (sum + arr[j] < k) {
                    sum = arr[j] + sum;
                    count++;
                }
                else {
                    break;
                }
            }
        }
        return count;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] array = { 1, 11, 2, 3, 15 };
        int k = 10;
        int size = array.Length;
        int count = countSubarray(array, size, k);
        Console.WriteLine(count);
    }
}
 
// This code is contributed by Sam007


PHP


Javascript


C++
// CPP program to count
// subarrays having sum
// less than k.
#include 
using namespace std;
 
// Function to find number
// of subarrays having sum
// less than k.
int countSubarrays(int arr[],
                   int n, int k)
{
    int start = 0, end = 0,
        count = 0, sum = arr[0];
 
    while (start < n && end < n) {
 
        // If sum is less than k,
        // move end by one position.
        // Update count and sum
        // accordingly.
        if (sum < k) {
            end++;
 
            if (end >= start)
                count += end - start;
 
            // For last element,
            // end may become n
            if (end < n)
                sum += arr[end];
        }
 
        // If sum is greater than or
        // equal to k, subtract
        // arr[start] from sum and
        // decrease sliding window by
        // moving start by one position
        else {
            sum -= arr[start];
            start++;
        }
    }
 
    return count;
}
 
// Driver Code
int main()
{
    int array[] = { 1, 11, 2, 3, 15 };
    int k = 10;
    int size = sizeof(array) / sizeof(array[0]);
    cout << countSubarrays(array, size, k);
}


Java
// Java program to count
// subarrays having sum
// less than k.
import java.io.*;
 
class GFG {
 
    // Function to find number
    // of subarrays having sum
    // less than k.
    static int countSubarray(int arr[],
                             int n, int k)
    {
        int start = 0, end = 0;
        int count = 0, sum = arr[0];
 
        while (start < n && end < n) {
 
            // If sum is less than k,
            // move end by one position.
            // Update count and sum
            // accordingly.
            if (sum < k) {
                end++;
 
                if (end >= start)
                    count += end - start;
 
                // For last element,
                // end may become n.
                if (end < n)
                    sum += arr[end];
            }
 
            // If sum is greater than or
            // equal to k, subtract
            // arr[start] from sum and
            // decrease sliding window by
            // moving start by one position
            else {
                sum -= arr[start];
                start++;
            }
        }
 
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int array[] = { 1, 11, 2, 3, 15 };
        int k = 10;
        int size = array.length;
        int count = countSubarray(array, size, k);
        System.out.println(count);
    }
}
 
// This code is contributed by Sam007


Python 3
# Python 3 program to count subarrays
# having sum less than k.
 
# Function to find number of subarrays
# having sum less than k.
def countSubarrays(arr, n, k):
 
    start = 0
    end = 0
    count = 0
    sum = arr[0]
 
    while (start < n and end < n) :
 
        # If sum is less than k, move end
        # by one position. Update count and
        # sum accordingly.
        if (sum < k) :
            end += 1
 
            if (end >= start):
                count += end - start
 
            # For last element, end may become n
            if (end < n):
                sum += arr[end]
 
        # If sum is greater than or equal to k,
        # subtract arr[start] from sum and
        # decrease sliding window by moving
        # start by one position
        else :
            sum -= arr[start]
            start += 1
 
    return count
 
# Driver Code
if __name__ == "__main__":
     
    array = [ 1, 11, 2, 3, 15 ]
    k = 10
    size = len(array)
    print(countSubarrays(array, size, k))
 
# This code is contributed by ita_c


C#
// C# program to count
// subarrays having sum
// less than k.
using System;
 
class GFG {
 
    // Function to find number
    // of subarrays having sum
    // less than k.
    static int countSubarray(int[] arr,
                             int n, int k)
    {
        int start = 0, end = 0;
        int count = 0, sum = arr[0];
 
        while (start < n && end < n) {
 
            // If sum is less than k,
            // move end by one position.
            // Update count and sum
            // accordingly.
            if (sum < k) {
                end++;
 
                if (end >= start)
                    count += end - start;
 
                // For last element,
                // end may become n.
                if (end < n)
                    sum += arr[end];
            }
 
            // If sum is greater than or
            // equal to k, subtract
            // arr[start] from sum and
            // decrease sliding window by
            // moving start by one position
            else {
                sum -= arr[start];
                start++;
            }
        }
 
        return count;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] array = { 1, 11, 2, 3, 15 };
        int k = 10;
        int size = array.Length;
        int count = countSubarray(array, size, k);
        Console.WriteLine(count);
    }
}
 
// This code is contributed by Sam007


PHP
= $start)
            $count += $end - $start;
 
            // For last element,
            // end may become n
            if ($end < $n)
            $sum += $arr[$end];
        }
 
        // If sum is greater than or
        // equal to k, subtract
        // arr[start] from sum and
        // decrease sliding window by
        // moving start by one position
        else
        {
            $sum -= $arr[$start];
            $start++;
        }
    }
 
    return $count;
}
 
    // Driver Code
    $array =array (1, 11, 2, 3, 15);
    $k = 10;
    $size = sizeof($array) ;
    echo countSubarrays($array, $size, $k);
 
// This code is contributed by ajit
?>


Javascript


输出 :
4

时间复杂度: O(n^2)。
一种有效的解决方案是基于可用于解决问题的滑动窗口技术。我们使用两个指针 start 和 end 来表示滑动窗口的起点和终点。 (并不是说我们需要找到连续的部分)。
最初开始和结束都指向数组的开头,即索引 0。现在,让我们尝试添加一个新元素 el。有两种可能的情况。
第一种情况:
如果 sum 小于 k,则将 end 增加一个位置。所以这一步产生的连续数组是(结束-开始)。我们还将 el 添加到先前的总和中。这样的数组与窗口的长度一样多。
第二种情况:
如果 sum 大于或等于 k,这意味着我们需要从 sum 中减去起始元素,以便 sum 再次小于 k。所以我们通过递增start来调整窗口的左边框。
我们遵循相同的过程,直到 end < 数组大小。
执行:

C++

// CPP program to count
// subarrays having sum
// less than k.
#include 
using namespace std;
 
// Function to find number
// of subarrays having sum
// less than k.
int countSubarrays(int arr[],
                   int n, int k)
{
    int start = 0, end = 0,
        count = 0, sum = arr[0];
 
    while (start < n && end < n) {
 
        // If sum is less than k,
        // move end by one position.
        // Update count and sum
        // accordingly.
        if (sum < k) {
            end++;
 
            if (end >= start)
                count += end - start;
 
            // For last element,
            // end may become n
            if (end < n)
                sum += arr[end];
        }
 
        // If sum is greater than or
        // equal to k, subtract
        // arr[start] from sum and
        // decrease sliding window by
        // moving start by one position
        else {
            sum -= arr[start];
            start++;
        }
    }
 
    return count;
}
 
// Driver Code
int main()
{
    int array[] = { 1, 11, 2, 3, 15 };
    int k = 10;
    int size = sizeof(array) / sizeof(array[0]);
    cout << countSubarrays(array, size, k);
}

Java

// Java program to count
// subarrays having sum
// less than k.
import java.io.*;
 
class GFG {
 
    // Function to find number
    // of subarrays having sum
    // less than k.
    static int countSubarray(int arr[],
                             int n, int k)
    {
        int start = 0, end = 0;
        int count = 0, sum = arr[0];
 
        while (start < n && end < n) {
 
            // If sum is less than k,
            // move end by one position.
            // Update count and sum
            // accordingly.
            if (sum < k) {
                end++;
 
                if (end >= start)
                    count += end - start;
 
                // For last element,
                // end may become n.
                if (end < n)
                    sum += arr[end];
            }
 
            // If sum is greater than or
            // equal to k, subtract
            // arr[start] from sum and
            // decrease sliding window by
            // moving start by one position
            else {
                sum -= arr[start];
                start++;
            }
        }
 
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int array[] = { 1, 11, 2, 3, 15 };
        int k = 10;
        int size = array.length;
        int count = countSubarray(array, size, k);
        System.out.println(count);
    }
}
 
// This code is contributed by Sam007

Python3

# Python 3 program to count subarrays
# having sum less than k.
 
# Function to find number of subarrays
# having sum less than k.
def countSubarrays(arr, n, k):
 
    start = 0
    end = 0
    count = 0
    sum = arr[0]
 
    while (start < n and end < n) :
 
        # If sum is less than k, move end
        # by one position. Update count and
        # sum accordingly.
        if (sum < k) :
            end += 1
 
            if (end >= start):
                count += end - start
 
            # For last element, end may become n
            if (end < n):
                sum += arr[end]
 
        # If sum is greater than or equal to k,
        # subtract arr[start] from sum and
        # decrease sliding window by moving
        # start by one position
        else :
            sum -= arr[start]
            start += 1
 
    return count
 
# Driver Code
if __name__ == "__main__":
     
    array = [ 1, 11, 2, 3, 15 ]
    k = 10
    size = len(array)
    print(countSubarrays(array, size, k))
 
# This code is contributed by ita_c

C#

// C# program to count
// subarrays having sum
// less than k.
using System;
 
class GFG {
 
    // Function to find number
    // of subarrays having sum
    // less than k.
    static int countSubarray(int[] arr,
                             int n, int k)
    {
        int start = 0, end = 0;
        int count = 0, sum = arr[0];
 
        while (start < n && end < n) {
 
            // If sum is less than k,
            // move end by one position.
            // Update count and sum
            // accordingly.
            if (sum < k) {
                end++;
 
                if (end >= start)
                    count += end - start;
 
                // For last element,
                // end may become n.
                if (end < n)
                    sum += arr[end];
            }
 
            // If sum is greater than or
            // equal to k, subtract
            // arr[start] from sum and
            // decrease sliding window by
            // moving start by one position
            else {
                sum -= arr[start];
                start++;
            }
        }
 
        return count;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] array = { 1, 11, 2, 3, 15 };
        int k = 10;
        int size = array.Length;
        int count = countSubarray(array, size, k);
        Console.WriteLine(count);
    }
}
 
// This code is contributed by Sam007

PHP

= $start)
            $count += $end - $start;
 
            // For last element,
            // end may become n
            if ($end < $n)
            $sum += $arr[$end];
        }
 
        // If sum is greater than or
        // equal to k, subtract
        // arr[start] from sum and
        // decrease sliding window by
        // moving start by one position
        else
        {
            $sum -= $arr[$start];
            $start++;
        }
    }
 
    return $count;
}
 
    // Driver Code
    $array =array (1, 11, 2, 3, 15);
    $k = 10;
    $size = sizeof($array) ;
    echo countSubarrays($array, $size, $k);
 
// This code is contributed by ajit
?>

Javascript


输出:
4

时间复杂度: O(n)。