📜  平均 K 的子数组数

📅  最后修改于: 2021-10-27 08:26:40             🧑  作者: Mango

给定一个大小为N的数组arr[] 任务是计算平均值完全等于k的子数组的数量。

例子:

朴素方法:解决问题的最简单方法是遍历所有子数组并计算它们的平均值。如果他们的平均值是K,则增加答案。

下面是朴素方法的实现:

C++
// C++ implementation of above approach
#include 
using namespace std;
 
// Function to count subarray having average
// exactly equal to K
int countKAverageSubarrays(int arr[], int n, int k)
{
 
    // To Store the final answer
    int res = 0;
 
    // Calculate all subarrays
    for (int L = 0; L < n; L++) {
        int sum = 0;
        for (int R = L; R < n; R++) {
            // Calculate required average
            sum += arr[R];
            int len = (R - L + 1);
 
            // Check if average
            // is equal to k
            if (sum % len == 0) {
                int avg = sum / len;
 
                // Required average found
                if (avg == k)
 
                    // Increment res
                    res++;
            }
        }
    }
    return res;
}
 
// Driver code
int main()
{
    // Given Input
    int K = 6;
    int arr[] = { 12, 5, 3, 10, 4, 8, 10, 12, -6, -1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countKAverageSubarrays(arr, N, K);
}


Java
// Java implementation of above approach
import java.io.*;
 
class GFG{
     
// Function to count subarray having average
// exactly equal to K
static int countKAverageSubarrays(int arr[], int n,
                                  int k)
{
     
    // To Store the final answer
    int res = 0;
 
    // Calculate all subarrays
    for(int L = 0; L < n; L++)
    {
        int sum = 0;
        for(int R = L; R < n; R++)
        {
             
            // Calculate required average
            sum += arr[R];
            int len = (R - L + 1);
 
            // Check if average
            // is equal to k
            if (sum % len == 0)
            {
                int avg = sum / len;
 
                // Required average found
                if (avg == k)
 
                    // Increment res
                    res++;
            }
        }
    }
    return res;
}
 
// Driver code
public static void main(String[] args)
{
     
    // Given Input
    int K = 6;
    int arr[] = { 12, 5, 3, 10, 4,
                   8, 10, 12, -6, -1 };
    int N = arr.length;
 
    // Function Call
    System.out.print(countKAverageSubarrays(arr, N, K));
}
}
 
// This code is contributed by shivanisinghss2110


Python3
# Python 3 implementation of above approach
 
# Function to count subarray having average
# exactly equal to K
def countKAverageSubarrays(arr, n, k):
    # To Store the final answer
    res = 0
 
    # Calculate all subarrays
    for L in range(n):
        sum = 0
        for R in range(L,n,1):
            # Calculate required average
            sum += arr[R]
            len1 = (R - L + 1)
 
            # Check if average
            # is equal to k
            if (sum % len1 == 0):
                avg = sum // len1
 
                # Required average found
                if (avg == k):
 
                    # Increment res
                    res += 1
             
    return res
 
# Driver code
if __name__ == '__main__':
    # Given Input
    K = 6
    arr = [12, 5, 3, 10, 4, 8, 10, 12, -6, -1]
    N = len(arr)
 
    # Function Call
    print(countKAverageSubarrays(arr, N, K))
 
    # This code is contributed by SURENDRA_GANGWAR.


C#
// C# implementation of above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count subarray having average
// exactly equal to K
static int countKAverageSubarrays(int []arr, int n, int k)
{
 
    // To Store the final answer
    int res = 0;
 
    // Calculate all subarrays
    for (int L = 0; L < n; L++)
    {
        int sum = 0;
        for (int R = L; R < n; R++)
        {
           
            // Calculate required average
            sum += arr[R];
            int len = (R - L + 1);
 
            // Check if average
            // is equal to k
            if (sum % len == 0) {
                int avg = sum / len;
 
                // Required average found
                if (avg == k)
 
                    // Increment res
                    res++;
            }
        }
    }
    return res;
}
 
// Driver code
public static void Main()
{
    // Given Input
    int K = 6;
    int []arr = { 12, 5, 3, 10, 4, 8, 10, 12, -6, -1 };
    int N = arr.Length;
 
    // Function Call
    Console.Write(countKAverageSubarrays(arr, N, K));
}
}
 
// This code is contributed by bgangwar59.


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count subarray having average
// exactly equal to K
int countKAverageSubarrays(int arr[], int n, int k)
{
    int result = 0, curSum = 0;
 
    // Store the frequency of prefix
    // sum of the array arr[]
    unordered_map mp;
 
    for (int i = 0; i < n; i++) {
        // Subtract k from each element,
        // then add it to curSum
        curSum += (arr[i] - k);
 
        // If curSum is 0 that means
        // sum[0...i] is 0 so increment
        // res
        if (curSum == 0)
            result++;
 
        // Check if curSum has occurred
        // before and if it has occurred
        // before, add it's frequency to
        // res
        if (mp.find(curSum) != mp.end())
            result += mp[curSum];
 
        // Increment the frequency
        // of curSum
        mp[curSum]++;
    }
 
    // Return result
    return result;
}
 
// Driver code
int main()
{
    // Given Input
    int K = 6;
    int arr[] = { 12, 5, 3, 10, 4, 8, 10, 12, -6, -1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countKAverageSubarrays(arr, N, K);
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to count subarray having average
// exactly equal to K
static int countKAverageSubarrays(int[] arr, int n,
                                  int k)
{
    int result = 1, curSum = 0;
 
    // Store the frequency of prefix
    // sum of the array arr[]
    HashMap mp = new HashMap();
 
    for(int i = 0; i < n; i++)
    {
         
        // Subtract k from each element,
        // then add it to curSum
        curSum += (arr[i] - k);
 
        // If curSum is 0 that means
        // sum[0...i] is 0 so increment
        // res
        if (curSum == 0)
            result++;
 
        // Check if curSum has occurred
        // before and if it has occurred
        // before, add it's frequency to
        // res
        if (mp.containsKey(curSum))
            result += mp.get(curSum);
 
        // Increment the frequency
        // of curSum
        mp.put(curSum, 1);
    }
 
    // Return result
    return result;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given Input
    int K = 6;
    int[] arr = { 12, 5, 3, 10, 4,
                  8, 10, 12, -6, -1 };
    int N = arr.length;
 
    // Function Call
    System.out.print(countKAverageSubarrays(arr, N, K));
}
}
 
// This code is contributed by sanjoy_62


Python3
# Python Program for the above approach
 
# Function to count subarray having average
# exactly equal to K
def countKAverageSubarrays(arr, n, k):
   
    result = 0
    curSum = 0
     
    # Store the frequency of prefix
    # sum of the array arr[]
    mp = dict()
     
    for i in range(0, n):
       
        # Subtract k from each element,
        # then add it to curSum
        curSum += (arr[i] - k)
         
        # If curSum is 0 that means
        # sum[0...i] is 0 so increment
        # res
        if (curSum == 0):
            result += 1
             
        # Check if curSum has occurred
        # before and if it has occurred
        # before, add it's frequency to
        # res
        if curSum in mp:
            result += mp[curSum]
             
        # Increment the frequency
        # of curSum
        if curSum in mp:
            mp[curSum] += 1
        else:
            mp[curSum] = 1
             
    # Return result
    return result
 
 
# Driver code
if __name__ == '__main__':
   
    # Given Input
    K = 6
    arr = [12, 5, 3, 10, 4, 8, 10, 12, -6, -1]
    N = len(arr)
 
    # Function Call
    print(countKAverageSubarrays(arr, N, K))
 
# This code is contributed by MuskanKalra1


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
 
public class GFG{
     
// Function to count subarray having average
// exactly equal to K
static int countKAverageSubarrays(int[] arr, int n,
                                  int k)
{
    int result = 1, curSum = 0;
 
    // Store the frequency of prefix
    // sum of the array []arr
    Dictionary mp = new Dictionary();
 
    for(int i = 0; i < n; i++)
    {
         
        // Subtract k from each element,
        // then add it to curSum
        curSum += (arr[i] - k);
 
        // If curSum is 0 that means
        // sum[0...i] is 0 so increment
        // res
        if (curSum == 0)
            result++;
 
        // Check if curSum has occurred
        // before and if it has occurred
        // before, add it's frequency to
        // res
        if (mp.ContainsKey(curSum))
            result += mp[curSum];
        else
        // Increment the frequency
        // of curSum
        mp.Add(curSum, 1);
    }
 
    // Return result
    return result;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given Input
    int K = 6;
    int[] arr = { 12, 5, 3, 10, 4,
                  8, 10, 12, -6, -1 };
    int N = arr.Length;
 
    // Function Call
    Console.Write(countKAverageSubarrays(arr, N, K));
}
}
 
 
// This code contributed by shikhasingrajput


Javascript


输出
4

时间复杂度: O(N^2)
辅助空间: O(1)

有效的方法:有效的解决方案基于以下观察结果:

请按照以下步骤解决此问题:

  • 初始化一个映射说, mp来存储数组arr[]的前缀和的频率
  • 初始化一个变量,比如curSum结果0。
  • 使用变量i在范围[0, N-1] 中迭代
    • 从当前元素中减去K ,然后将其添加到curSum。
    • 如果curSum0,子阵列具有平均等于0被发现,由1,从而增加的结果
    • 如果在使用地图之前已经发生了curSum 。如果之前发生过,则将之前发生的次数添加到结果中,然后使用地图增加curSum的频率。
  • 完成以上步骤后,打印结果作为答案。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to count subarray having average
// exactly equal to K
int countKAverageSubarrays(int arr[], int n, int k)
{
    int result = 0, curSum = 0;
 
    // Store the frequency of prefix
    // sum of the array arr[]
    unordered_map mp;
 
    for (int i = 0; i < n; i++) {
        // Subtract k from each element,
        // then add it to curSum
        curSum += (arr[i] - k);
 
        // If curSum is 0 that means
        // sum[0...i] is 0 so increment
        // res
        if (curSum == 0)
            result++;
 
        // Check if curSum has occurred
        // before and if it has occurred
        // before, add it's frequency to
        // res
        if (mp.find(curSum) != mp.end())
            result += mp[curSum];
 
        // Increment the frequency
        // of curSum
        mp[curSum]++;
    }
 
    // Return result
    return result;
}
 
// Driver code
int main()
{
    // Given Input
    int K = 6;
    int arr[] = { 12, 5, 3, 10, 4, 8, 10, 12, -6, -1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countKAverageSubarrays(arr, N, K);
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to count subarray having average
// exactly equal to K
static int countKAverageSubarrays(int[] arr, int n,
                                  int k)
{
    int result = 1, curSum = 0;
 
    // Store the frequency of prefix
    // sum of the array arr[]
    HashMap mp = new HashMap();
 
    for(int i = 0; i < n; i++)
    {
         
        // Subtract k from each element,
        // then add it to curSum
        curSum += (arr[i] - k);
 
        // If curSum is 0 that means
        // sum[0...i] is 0 so increment
        // res
        if (curSum == 0)
            result++;
 
        // Check if curSum has occurred
        // before and if it has occurred
        // before, add it's frequency to
        // res
        if (mp.containsKey(curSum))
            result += mp.get(curSum);
 
        // Increment the frequency
        // of curSum
        mp.put(curSum, 1);
    }
 
    // Return result
    return result;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given Input
    int K = 6;
    int[] arr = { 12, 5, 3, 10, 4,
                  8, 10, 12, -6, -1 };
    int N = arr.length;
 
    // Function Call
    System.out.print(countKAverageSubarrays(arr, N, K));
}
}
 
// This code is contributed by sanjoy_62

蟒蛇3

# Python Program for the above approach
 
# Function to count subarray having average
# exactly equal to K
def countKAverageSubarrays(arr, n, k):
   
    result = 0
    curSum = 0
     
    # Store the frequency of prefix
    # sum of the array arr[]
    mp = dict()
     
    for i in range(0, n):
       
        # Subtract k from each element,
        # then add it to curSum
        curSum += (arr[i] - k)
         
        # If curSum is 0 that means
        # sum[0...i] is 0 so increment
        # res
        if (curSum == 0):
            result += 1
             
        # Check if curSum has occurred
        # before and if it has occurred
        # before, add it's frequency to
        # res
        if curSum in mp:
            result += mp[curSum]
             
        # Increment the frequency
        # of curSum
        if curSum in mp:
            mp[curSum] += 1
        else:
            mp[curSum] = 1
             
    # Return result
    return result
 
 
# Driver code
if __name__ == '__main__':
   
    # Given Input
    K = 6
    arr = [12, 5, 3, 10, 4, 8, 10, 12, -6, -1]
    N = len(arr)
 
    # Function Call
    print(countKAverageSubarrays(arr, N, K))
 
# This code is contributed by MuskanKalra1

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
 
public class GFG{
     
// Function to count subarray having average
// exactly equal to K
static int countKAverageSubarrays(int[] arr, int n,
                                  int k)
{
    int result = 1, curSum = 0;
 
    // Store the frequency of prefix
    // sum of the array []arr
    Dictionary mp = new Dictionary();
 
    for(int i = 0; i < n; i++)
    {
         
        // Subtract k from each element,
        // then add it to curSum
        curSum += (arr[i] - k);
 
        // If curSum is 0 that means
        // sum[0...i] is 0 so increment
        // res
        if (curSum == 0)
            result++;
 
        // Check if curSum has occurred
        // before and if it has occurred
        // before, add it's frequency to
        // res
        if (mp.ContainsKey(curSum))
            result += mp[curSum];
        else
        // Increment the frequency
        // of curSum
        mp.Add(curSum, 1);
    }
 
    // Return result
    return result;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given Input
    int K = 6;
    int[] arr = { 12, 5, 3, 10, 4,
                  8, 10, 12, -6, -1 };
    int N = arr.Length;
 
    // Function Call
    Console.Write(countKAverageSubarrays(arr, N, K));
}
}
 
 
// This code contributed by shikhasingrajput

Javascript


输出
4

时间复杂度: O(N)
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程