📜  大小为K的所有子数组的总和

📅  最后修改于: 2021-04-27 09:25:26             🧑  作者: Mango

给定一个数组arr []和一个整数K ,任务是计算大小为K的所有子数组的总和。
例子:

天真的方法:天真的方法将生成大小为K的所有子数组,并使用迭代找到每个子数组的总和。
下面是上述方法的实现:

C++
// C++ implementaion to find the sum
// of all subarrays of size K
 
#include 
using namespace std;
 
// Function to find the sum of
// all subarrays of size K
int calcSum(int arr[], int n, int k)
{
 
    // Loop to consider every
    // subarray of size K
    for (int i = 0; i <= n - k; i++) {
         
        // Initialize sum = 0
        int sum = 0;
 
        // Calculate sum of all elements
        // of current subarray
        for (int j = i; j < k + i; j++)
            sum += arr[j];
 
        // Print sum of each subarray
        cout << sum << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    // Function Call
    calcSum(arr, n, k);
 
    return 0;
}


Java
// Java implementaion to find the sum
// of all subarrays of size K
class GFG{
  
// Function to find the sum of
// all subarrays of size K
static void calcSum(int arr[], int n, int k)
{
  
    // Loop to consider every
    // subarray of size K
    for (int i = 0; i <= n - k; i++) {
          
        // Initialize sum = 0
        int sum = 0;
  
        // Calculate sum of all elements
        // of current subarray
        for (int j = i; j < k + i; j++)
            sum += arr[j];
  
        // Print sum of each subarray
        System.out.print(sum+ " ");
    }
}
  
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = arr.length;
    int k = 3;
  
    // Function Call
    calcSum(arr, n, k);
}
}
 
// This code is contributed by Rajput-Ji


C#
// C# implementaion to find the sum
// of all subarrays of size K
using System;
 
class GFG 
{
   
    // Function to find the sum of
    // all subarrays of size K
    static  void calcSum(int[] arr, int n, int k)
    {
     
        // Loop to consider every
        // subarray of size K
        for (int i = 0; i <= n - k; i++) {
             
            // Initialize sum = 0
            int sum = 0;
     
            // Calculate sum of all elements
            // of current subarray
            for (int j = i; j < k + i; j++)
                sum += arr[j];
     
            // Print sum of each subarray
            Console.Write(sum + " ");
        }
    }
     
    // Driver Code
    static void Main()
    {
        int[] arr = new int[] { 1, 2, 3, 4, 5, 6 };
        int n = arr.Length;
        int k = 3;
     
        // Function Call
        calcSum(arr, n, k);
     
    }
}
 
// This code is contributed by shubhamsingh10


Python3
# Python3 implementaion to find the sum
# of all subarrays of size K
 
# Function to find the sum of
# all subarrays of size K
def calcSum(arr, n, k):
 
    # Loop to consider every
    # subarray of size K
    for i in range(n - k + 1):
         
        # Initialize sum = 0
        sum = 0
 
        # Calculate sum of all elements
        # of current subarray
        for j in range(i, k + i):
            sum += arr[j]
 
        # Prsum of each subarray
        print(sum, end=" ")
 
# Driver Code
arr=[1, 2, 3, 4, 5, 6]
n = len(arr)
k = 3
 
# Function Call
calcSum(arr, n, k)
 
# This code is contributed by mohit kumar 29


Javascript


C++
// C++ implementaion to find the sum
// of all subarrays of size K
 
#include 
using namespace std;
 
// Function to find the sum of
// all subarrays of size K
int calcSum(int arr[], int n, int k)
{
    // Initialize sum = 0
    int sum = 0;
 
    // Consider first subarray of size k
    // Store the sum of elements
    for (int i = 0; i < k; i++)
        sum += arr[i];
 
    // Print the current sum
    cout << sum << " ";
 
    // Consider every subarray of size k
    // Remove first element and add current
    // element to the window
    for (int i = k; i < n; i++) {
         
        // Add the element which enters
        // into the window and substract
        // the element which pops out from
        // the window of the size K
        sum = (sum - arr[i - k]) + arr[i];
         
        // Print the sum of subarray
        cout << sum << " ";
    }
}
 
// Drivers Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
     
    // Function Call
    calcSum(arr, n, k);
 
    return 0;
}


Java
// Java implementaion to find the sum
// of all subarrays of size K
class GFG{
 
// Function to find the sum of
// all subarrays of size K
static void calcSum(int arr[], int n, int k)
{
    // Initialize sum = 0
    int sum = 0;
 
    // Consider first subarray of size k
    // Store the sum of elements
    for (int i = 0; i < k; i++)
        sum += arr[i];
 
    // Print the current sum
    System.out.print(sum+ " ");
 
    // Consider every subarray of size k
    // Remove first element and add current
    // element to the window
    for (int i = k; i < n; i++) {
         
        // Add the element which enters
        // into the window and substract
        // the element which pops out from
        // the window of the size K
        sum = (sum - arr[i - k]) + arr[i];
         
        // Print the sum of subarray
        System.out.print(sum+ " ");
    }
}
 
// Drivers Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = arr.length;
    int k = 3;
     
    // Function Call
    calcSum(arr, n, k);
}
}
 
// This code is contributed by sapnasingh4991


Python3
# Python3 implementaion to find the sum
# of all subarrays of size K
 
# Function to find the sum of
# all subarrays of size K
def calcSum(arr, n, k):
 
    # Initialize sum = 0
    sum = 0
 
    # Consider first subarray of size k
    # Store the sum of elements
    for i in range( k):
        sum += arr[i]
 
    # Print the current sum
    print( sum ,end= " ")
 
    # Consider every subarray of size k
    # Remove first element and add current
    # element to the window
    for i in range(k,n):
         
        # Add the element which enters
        # into the window and substract
        # the element which pops out from
        # the window of the size K
        sum = (sum - arr[i - k]) + arr[i]
         
        # Print the sum of subarray
        print( sum ,end=" ")
 
# Drivers Code
if __name__ == "__main__":
 
    arr = [ 1, 2, 3, 4, 5, 6 ]
    n = len(arr)
    k = 3
     
    # Function Call
    calcSum(arr, n, k)
 
# This code is contributed by chitranayal


C#
// C# implementaion to find the sum
// of all subarrays of size K
using System;
 
class GFG{
  
// Function to find the sum of
// all subarrays of size K
static void calcSum(int []arr, int n, int k)
{
    // Initialize sum = 0
    int sum = 0;
  
    // Consider first subarray of size k
    // Store the sum of elements
    for (int i = 0; i < k; i++)
        sum += arr[i];
  
    // Print the current sum
    Console.Write(sum+ " ");
  
    // Consider every subarray of size k
    // Remove first element and add current
    // element to the window
    for (int i = k; i < n; i++) {
          
        // Add the element which enters
        // into the window and substract
        // the element which pops out from
        // the window of the size K
        sum = (sum - arr[i - k]) + arr[i];
          
        // Print the sum of subarray
        Console.Write(sum + " ");
    }
}
  
// Drivers Code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 3, 4, 5, 6 };
    int n = arr.Length;
    int k = 3;
      
    // Function Call
    calcSum(arr, n, k);
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
6 9 12 15

性能分析:

  • 时间复杂度:与上述方法一样,有两个循环,其中第一个循环运行(N – K)次,第二个循环运行K次。因此,时间复杂度将为O(N * K)
  • 辅助空间复杂度:与上述方法一样,没有使用额外的空间。因此,辅助空间复杂度将为O(1)

高效方法:使用滑动窗口这个想法是使用滑动窗口方法来查找数组中所有可能的子数组的总和。

  • 对于[0,K]范围内的每个大小,找到大小为K的第一个窗口的总和,并将其存储在数组中。
  • 然后,对于[K,N]范围内的每个大小,添加对滑动窗口有贡献的下一个元素,并减去从窗口弹出的元素。
// Adding the element which
// adds into the new window
sum = sum + arr[j]

// Subtracting the element which
// pops out from the window
sum = sum - arr[j-k]

where sum is the variable to store the result
      arr is the given array
      j is the loop variable in range [K, N]

下面是上述方法的实现:

C++

// C++ implementaion to find the sum
// of all subarrays of size K
 
#include 
using namespace std;
 
// Function to find the sum of
// all subarrays of size K
int calcSum(int arr[], int n, int k)
{
    // Initialize sum = 0
    int sum = 0;
 
    // Consider first subarray of size k
    // Store the sum of elements
    for (int i = 0; i < k; i++)
        sum += arr[i];
 
    // Print the current sum
    cout << sum << " ";
 
    // Consider every subarray of size k
    // Remove first element and add current
    // element to the window
    for (int i = k; i < n; i++) {
         
        // Add the element which enters
        // into the window and substract
        // the element which pops out from
        // the window of the size K
        sum = (sum - arr[i - k]) + arr[i];
         
        // Print the sum of subarray
        cout << sum << " ";
    }
}
 
// Drivers Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
     
    // Function Call
    calcSum(arr, n, k);
 
    return 0;
}

Java

// Java implementaion to find the sum
// of all subarrays of size K
class GFG{
 
// Function to find the sum of
// all subarrays of size K
static void calcSum(int arr[], int n, int k)
{
    // Initialize sum = 0
    int sum = 0;
 
    // Consider first subarray of size k
    // Store the sum of elements
    for (int i = 0; i < k; i++)
        sum += arr[i];
 
    // Print the current sum
    System.out.print(sum+ " ");
 
    // Consider every subarray of size k
    // Remove first element and add current
    // element to the window
    for (int i = k; i < n; i++) {
         
        // Add the element which enters
        // into the window and substract
        // the element which pops out from
        // the window of the size K
        sum = (sum - arr[i - k]) + arr[i];
         
        // Print the sum of subarray
        System.out.print(sum+ " ");
    }
}
 
// Drivers Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = arr.length;
    int k = 3;
     
    // Function Call
    calcSum(arr, n, k);
}
}
 
// This code is contributed by sapnasingh4991

Python3

# Python3 implementaion to find the sum
# of all subarrays of size K
 
# Function to find the sum of
# all subarrays of size K
def calcSum(arr, n, k):
 
    # Initialize sum = 0
    sum = 0
 
    # Consider first subarray of size k
    # Store the sum of elements
    for i in range( k):
        sum += arr[i]
 
    # Print the current sum
    print( sum ,end= " ")
 
    # Consider every subarray of size k
    # Remove first element and add current
    # element to the window
    for i in range(k,n):
         
        # Add the element which enters
        # into the window and substract
        # the element which pops out from
        # the window of the size K
        sum = (sum - arr[i - k]) + arr[i]
         
        # Print the sum of subarray
        print( sum ,end=" ")
 
# Drivers Code
if __name__ == "__main__":
 
    arr = [ 1, 2, 3, 4, 5, 6 ]
    n = len(arr)
    k = 3
     
    # Function Call
    calcSum(arr, n, k)
 
# This code is contributed by chitranayal

C#

// C# implementaion to find the sum
// of all subarrays of size K
using System;
 
class GFG{
  
// Function to find the sum of
// all subarrays of size K
static void calcSum(int []arr, int n, int k)
{
    // Initialize sum = 0
    int sum = 0;
  
    // Consider first subarray of size k
    // Store the sum of elements
    for (int i = 0; i < k; i++)
        sum += arr[i];
  
    // Print the current sum
    Console.Write(sum+ " ");
  
    // Consider every subarray of size k
    // Remove first element and add current
    // element to the window
    for (int i = k; i < n; i++) {
          
        // Add the element which enters
        // into the window and substract
        // the element which pops out from
        // the window of the size K
        sum = (sum - arr[i - k]) + arr[i];
          
        // Print the sum of subarray
        Console.Write(sum + " ");
    }
}
  
// Drivers Code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 3, 4, 5, 6 };
    int n = arr.Length;
    int k = 3;
      
    // Function Call
    calcSum(arr, n, k);
}
}
 
// This code is contributed by 29AjayKumar

Java脚本


输出:
6 9 12 15

性能分析:

  • 时间复杂度:与上述方法一样,有一个循环需要O(N)时间。因此,时间复杂度将为O(N)
  • 辅助空间复杂度:与上述方法一样,没有使用额外的空间。因此,辅助空间复杂度将为O(1)