Maximum number of Perfect Numbers present in a subarray of size K

Given an array arr[ ] consisting of N integers, the task is to determine the maximum number of perfect Numbers in any subarray of size K.
Examples:
Input: arr[ ] = {28, 2, 3, 6, 496, 99, 8128, 24}, K = 4
Output: 3
Explanation: The sub-array {6, 496, 99, 8128} has 3 perfect numbers which is maximum.Input: arr[ ]= {1, 2, 3, 6}, K=2
Output: 1
Naive Approach: The approach is to generate all possible subarrays of size K and for each subarray, count the number of elements that are a Perfect Number. Print the maximum count obtained for any subarray.
Time Complexity: O(N*K)
Auxiliary Space: O(1)
Efficient Approach:Â
To optimize the above approach, convert the given array arr[ ] into a binary array where the ith element is 1 if it is a Perfect Number. Otherwise, the ith element is 0. Therefore, the problem reduces to finding the maximum sum subarray of size K in the binary array using the Sliding Window technique. Follow the steps below to solve the problem:
- Traverse the array and for each element of the array arr[], check if it is a Perfect Number or not.
- If arr[i] is a Perfect Number then convert arr[i] equal to 1. Otherwise, convert arr[i] equal to 0.
- To check if a number is a perfect number or not:
- Initialize a variable sum to store the sum of divisors.
- Traverse every number in the range [1, arr[i] – 1] and check if it is a divisor of arr[i] or not. Add all the divisors.
- If the sum of all the divisors is equal to arr[i], then the number is a perfect number. Otherwise, the number is not a Perfect Number.
- Compute the sum of the first subarray of size K in the modified array.
- Using the sliding window technique, find the maximum sum of a subarray from all possible subarrays of size K.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to check a number// is Perfect Number or notint 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 Kint 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 arrayint 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 Codeint 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 approachimport java.util.*;class GFG{Â
// Function to check a number// is Perfect Number or notstatic 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 Kstatic 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 arraystatic 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 Codepublic 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 notdef 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 Kdef 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 arraydef 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 Codeif __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 approachusing System;class GFG{Â
// Function to check a number// is Perfect Number or notstatic 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 Kstatic 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 arraystatic 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 Codepublic 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
<script>Â
// Javascript program for the above approachÂ
// Function to check a number// is Perfect Number or notfunction isPerfect(N){         // Stores sum of divisors    let sum = 1;         // Find all divisors and    // add them    for(let 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 Kfunction maxSum(arr, N, K){         // If k is greater than N    if (N < K)    {        document.write("Invalid");        return -1;    }         // Compute sum of first    // window of size K    let res = 0;         for(let 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    let curr_sum = res;         for(let 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 arrayfunction max_PerfectNumbers(arr, N, K){         // The given array is converted    // into binary array    for(let i = 0; i < N; i++)    {        arr[i] = isPerfect(arr[i]) ==                  1 ? 1 : 0;    }    return maxSum(arr, N, K);}Â
// Driver Codelet arr = [ 28, 2, 3, 6, 496,            99, 8128, 24 ];let K = 4;let N = arr.length;Â
document.write(max_PerfectNumbers(arr, N, K));Â
// This code is contributed by target_2Â Â Â Â
</script> |
Output:
3
Time Complexity: O( N * sqrt(N) Â )
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



