📜  大小为K的子数组中存在的最大实数个数

📅  最后修改于: 2021-05-19 18:15:47             🧑  作者: Mango

给定一个由N个整数组成的数组arr [] ,任务是确定大小为K的任何子数组中的理想数的最大数量。

例子:

天真的方法:该方法是生成大小为K的所有可能的子数组,并为每个子数组计算为完美数的元素数。打印任何子数组获得的最大计数。

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

高效方法:
为了优化上述方法,请将给定数组arr []转换为二进制数组,如果第i元素为“完美数”,则i元素为1 。否则,第i元素为0 。因此,问题减少到使用滑动窗口技术在二进制数组中找到大小为K的最大和子数组。请按照以下步骤解决问题:

  1. 遍历数组,并为数组arr []的每个元素检查其是否为完美数。
  2. 如果arr [i]是一个完美数,则将arr [i]转换为等于1。否则,将arr [i]转换为等于0
  3. 要检查一个数字是否是一个完美的数字,请执行以下操作:
    1. 初始化变量以存储除数之和。
    2. 遍历[1,arr [i] – 1]范围内的每个数字,并检查它是否为arr [i]的除数。添加所有除数。
    3. 如果所有除数的总和等于arr [i] ,则该数字为一个理想数。否则,该数字不是完美数字
  4. 计算修改后的数组中大小为K的第一个子数组的总和。
  5. 使用滑动窗口技术,从大小为K的所有可能的子数组中找到一个子数组的最大和。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check a number
// is Perfect Number or not
int isPerfect(int N)
{
    // Stores sum of divisors
    int sum = 1;
 
    // Find all divisors and add them
    for (int i = 2; i < sqrt(N); i++)
    {
 
        if (N % i == 0) {
 
            if (i == N / i)
            {
 
                sum += i;
            }
            else
            {
 
                sum += i + N / i;
            }
        }
    }
 
    // If sum of divisors
    // is equal to N
    if (sum == N && N != 1)
        return 1;
 
    return 0;
}
 
// Function to return maximum
// sum of a subarray of size K
int maxSum(int arr[], int N, int K)
{
    // If k is greater than N
    if (N < K)
    {
 
        cout << "Invalid";
        return -1;
    }
 
    // Compute sum of first window of size K
    int res = 0;
    for (int i = 0; i < K; i++)
    {
 
        res += arr[i];
    }
 
    // Compute sums of remaining windows by
    // removing first element of previous
    // window and adding last element of
    // current window
    int curr_sum = res;
    for (int i = K; i < N; i++)
    {
 
        curr_sum += arr[i] - arr[i - K];
        res = max(res, curr_sum);
    }
 
    // return the answer
    return res;
}
 
// Function to find all the
// perfect numbers in the array
int max_PerfectNumbers(int arr[], int N, int K)
{
    // The given array is converted into binary array
    for (int i = 0; i < N; i++)
    {
 
        arr[i] = isPerfect(arr[i]) ? 1 : 0;
    }
 
    return maxSum(arr, N, K);
}
 
// Driver Code
int main()
{
    int arr[] = { 28, 2, 3, 6, 496, 99, 8128, 24 };
    int K = 4;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << max_PerfectNumbers(arr, N, K);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
class GFG{
 
// Function to check a number
// is Perfect Number or not
static int isPerfect(int N)
{
  // Stores sum of divisors
  int sum = 1;
 
  // Find all divisors and
  // add them
  for (int i = 2;
           i < Math.sqrt(N); i++)
  {
    if (N % i == 0)
    {
      if (i == N / i)
      {
        sum += i;
      }
      else
      {
        sum += i + N / i;
      }
    }
  }
 
  // If sum of divisors
  // is equal to N
  if (sum == N && N != 1)
    return 1;
   
  return 0;
}
 
// Function to return maximum
// sum of a subarray of size K
static int maxSum(int arr[],
                  int N, int K)
{
  // If k is greater than N
  if (N < K)
  {
    System.out.print("Invalid");
    return -1;
  }
 
  // Compute sum of first
  // window of size K
  int res = 0;
   
  for (int i = 0; i < K; i++)
  {
    res += arr[i];
  }
 
  // Compute sums of remaining windows by
  // removing first element of previous
  // window and adding last element of
  // current window
  int curr_sum = res;
   
  for (int i = K; i < N; i++)
  {
    curr_sum += arr[i] - arr[i - K];
    res = Math.max(res, curr_sum);
  }
 
  // return the answer
  return res;
}
 
// Function to find all the
// perfect numbers in the array
static int max_PerfectNumbers(int arr[],
                              int N, int K)
{
  // The given array is converted
  // into binary array
  for (int i = 0; i < N; i++)
  {
    arr[i] = isPerfect(arr[i]) ==
             1 ? 1 : 0;
  }
 
  return maxSum(arr, N, K);
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {28, 2, 3, 6, 496,
               99, 8128, 24};
  int K = 4;
  int N = arr.length;
  System.out.print(max_PerfectNumbers(arr,
                                      N, K));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program for the above approach
 
# Function to check a number
# is Perfect Number or not
def isPerfect(N):
     
    # Stores sum of divisors
    sum = 1
 
    # Find all divisors and add them
    for i in range(2, N):
        if i * i > N:
            break
 
        if (N % i == 0):
            if (i == N // i):
                sum += i
            else:
                sum += i + N // i
 
    # If sum of divisors
    # is equal to N
    if (sum == N and N != 1):
        return 1
 
    return 0
 
# Function to return maximum
# sum of a subarray of size K
def maxSum(arr, N, K):
     
    # If k is greater than N
    if (N < K):
        print("Invalid")
        return -1
 
    # Compute sum of first
    # window of size K
    res = 0
     
    for i in range(K):
        res += arr[i]
 
    # Compute sums of remaining windows by
    # removing first element of previous
    # window and adding last element of
    # current window
    curr_sum = res
     
    for i in range(K, N):
        curr_sum += arr[i] - arr[i - K]
        res = max(res, curr_sum)
         
    # print(res)
 
    # Return the answer
    return res
 
# Function to find all the
# perfect numbers in the array
def max_PerfectNumbers(arr, N, K):
     
    # The given array is converted
    # into binary array
    for i in range(N):
        if isPerfect(arr[i]):
            arr[i] = 1
        else:
            arr[i] = 0
 
    return maxSum(arr, N, K)
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 28, 2, 3, 6,
            496, 99, 8128, 24 ]
    K = 4
    N = len(arr)
 
    print(max_PerfectNumbers(arr, N, K))
     
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
class GFG{
 
// Function to check a number
// is Perfect Number or not
static int isPerfect(int N)
{
  // Stores sum of divisors
  int sum = 1;
 
  // Find all divisors and
  // add them
  for (int i = 2;
           i < Math.Sqrt(N); i++)
  {
    if (N % i == 0)
    {
      if (i == N / i)
      {
        sum += i;
      }
      else
      {
        sum += i + N / i;
      }
    }
  }
 
  // If sum of divisors
  // is equal to N
  if (sum == N && N != 1)
    return 1;
   
  return 0;
}
 
// Function to return maximum
// sum of a subarray of size K
static int maxSum(int []arr,
                  int N, int K)
{
  // If k is greater than N
  if (N < K)
  {
    Console.Write("Invalid");
    return -1;
  }
 
  // Compute sum of first
  // window of size K
  int res = 0;
   
  for (int i = 0; i < K; i++)
  {
    res += arr[i];
  }
 
  // Compute sums of remaining
  // windows by removing first
  // element of previous window
  // and adding last element of
  // current window
  int curr_sum = res;
   
  for (int i = K; i < N; i++)
  {
    curr_sum += arr[i] - arr[i - K];
    res = Math.Max(res, curr_sum);
  }
 
  // return the answer
  return res;
}
 
// Function to find all the
// perfect numbers in the array
static int max_PerfectNumbers(int []arr,
                              int N, int K)
{
  // The given array is converted
  // into binary array
  for (int i = 0; i < N; i++)
  {
    arr[i] = isPerfect(arr[i]) ==
             1 ? 1 : 0;
  }
 
  return maxSum(arr, N, K);
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = {28, 2, 3, 6, 496,
               99, 8128, 24};
  int K = 4;
  int N = arr.Length;
  Console.Write(max_PerfectNumbers(arr,
                                   N, K));
}
}
 
// This code is contributed by Amit Katiyar


输出:

3

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