Count numbers whose maximum sum of distinct digit | C ++ implementation to find the Maximum count of numbers whose sum of distinct digit - sum less than or equal to the given number ; Function to find the digit - sum of a number ; Loop to iterate the number digit - wise to find digit - sum ; variable to store last digit ; Function to find the count of number ; Vector to store the Sum of Digits ; Sum of digits for each element in vector ; Sorting the digitSum vector ; Removing the duplicate elements ; Count variable to store the Count ; Finding the Count of Numbers ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int SumofDigits ( int digit ) { int sum = 0 ; while ( digit != 0 ) { int rem = digit % 10 ; sum += rem ; digit /= 10 ; } return sum ; } int findCountofNumbers ( int arr [ ] , int n , int M ) { vector < int > SumDigits ; for ( int i = 0 ; i < n ; i ++ ) { int s = SumofDigits ( arr [ i ] ) ; SumDigits . push_back ( s ) ; } sort ( SumDigits . begin ( ) , SumDigits . end ( ) ) ; vector < int > :: iterator ip ; ip = unique ( SumDigits . begin ( ) , SumDigits . end ( ) ) ; SumDigits . resize ( distance ( SumDigits . begin ( ) , ip ) ) ; int count = 0 ; int sum = 0 ; for ( int i = 0 ; i < SumDigits . size ( ) ; i ++ ) { if ( sum > M ) break ; sum += SumDigits [ i ] ; if ( sum <= M ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 1 , 45 , 16 , 17 , 219 , 32 , 22 } , M = 10 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findCountofNumbers ( arr , n , M ) ; return 0 ; }