Maximum number of Armstrong Numbers present in a subarray of size K | C ++ program for the above approach ; Function to calculate the value of x raised to the power y in O ( log y ) ; Base Case ; If the power y is even ; Otherwise ; Function to calculate the order of the number , i . e . count of digits ; Stores the total count of digits ; Iterate until num is 0 ; Function to check a number is an Armstrong Number or not ; Find the order of the number ; Check for Armstrong Number ; If Armstrong number condition is satisfied ; Utility function to find the maximum sum of a subarray of size K ; If k is greater than N ; Find the sum of first subarray of size K ; Find the sum of the remaining subarray ; Return the maximum sum of subarray of size K ; Function to find all the Armstrong Numbers in the array ; Traverse the array arr [ ] ; If arr [ i ] is an Armstrong Number , then replace it by 1. Otherwise , 0 ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int x , unsigned int y ) { if ( y == 0 ) return 1 ; if ( y % 2 == 0 ) return power ( x , y / 2 ) * power ( x , y / 2 ) ; return x * power ( x , y / 2 ) * power ( x , y / 2 ) ; } int order ( int num ) { int count = 0 ; while ( num ) { count ++ ; num = num / 10 ; } return count ; } int isArmstrong ( int N ) { int r = order ( N ) ; int temp = N , sum = 0 ; while ( temp ) { int d = temp % 10 ; sum += power ( d , r ) ; temp = temp / 10 ; } return ( sum == N ) ; } int maxSum ( int arr [ ] , int N , int K ) { if ( N < K ) { return -1 ; } int res = 0 ; for ( int i = 0 ; i < K ; i ++ ) { res += arr [ i ] ; } int curr_sum = res ; for ( int i = K ; i < N ; i ++ ) { curr_sum += arr [ i ] - arr [ i - K ] ; res = max ( res , curr_sum ) ; } return res ; } int maxArmstrong ( int arr [ ] , int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = isArmstrong ( arr [ i ] ) ; } return maxSum ( arr , N , K ) ; } int main ( ) { int arr [ ] = { 28 , 2 , 3 , 6 , 153 , 99 , 828 , 24 } ; int K = 6 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxArmstrong ( arr , N , K ) ; return 0 ; }