📜  大小为 K 的子数组中存在的最大完全数数

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

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

例子:

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

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

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

  1. 遍历数组,对于数组arr[] 的每个元素,检查它是否是一个完美数。
  2. 如果arr[i]是完全数,则将arr[i]转换为等于1。否则,将arr[i]转换为等于0
  3. 检查一个数是否为完全数:
    1. 初始化一个变量sum来存储除数的总和。
    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


Javascript


输出:

3

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live