Maximize sum of array by repeatedly removing an element from pairs whose concatenation is a multiple of 3 | C ++ approach for the above approach ; Function to calculate sum of digits of an integer ; Function to calculate maximum sum of array after removing pairs whose concatenation is divisible by 3 ; Stores the sum of digits of array element ; Find the sum of digits ; If i is divisible by 3 ; Otherwise , if i modulo 3 is 1 ; Otherwise , if i modulo 3 is 2 ; Return the resultant sum of array elements ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getSum ( int n ) { int ans = 0 ; string arr = to_string ( n ) ; for ( int i = 0 ; i < arr . length ( ) ; i ++ ) { ans += int ( arr [ i ] ) ; } return ans ; } void getMax ( int arr [ ] , int n ) { int maxRem0 = 0 ; int rem1 = 0 ; int rem2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int digitSum = getSum ( arr [ i ] ) ; if ( digitSum % 3 == 0 ) maxRem0 = max ( maxRem0 , arr [ i ] ) ; else if ( digitSum % 3 == 1 ) rem1 += arr [ i ] ; else rem2 += arr [ i ] ; } cout << ( maxRem0 + max ( rem1 , rem2 ) ) ; } int main ( ) { int arr [ ] = { 23 , 12 , 43 , 3 , 56 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getMax ( arr , n ) ; }