Find the index of the smallest element to be removed to make sum of array divisible by K | C ++ program to implement the above approach ; Function to find index of the smallest array element required to be removed to make sum divisible by K ; Stores sum of array elements ; Stores index of the smallest element removed from the array to make sum divisible by K ; Stores the smallest element removed from the array to make sum divisible by K ; Traverse the array , arr [ ] ; Update sum ; Traverse the array arr [ ] ; Calculate remaining sum ; If sum is divisible by K ; If res == - 1 or mini is greater than arr [ i ] ; Update res and mini ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findIndex ( int arr [ ] , int n , int K ) { int sum = 0 ; int res = -1 ; int mini = 1e9 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { int temp = sum - arr [ i ] ; if ( temp % K == 0 ) { if ( res == -1 mini > arr [ i ] ) { res = i + 1 ; mini = arr [ i ] ; } } } return res ; } int main ( ) { int arr [ ] = { 14 , 7 , 8 , 2 , 4 } ; int K = 7 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findIndex ( arr , N , K ) ; return 0 ; }