Find the index of the smallest element to be removed to make sum of array divisible by K | 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
function findIndex ( arr , n , K ) { let sum = 0 ; let res = - 1 ; let mini = parseInt ( 1e9 ) ; for ( let i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } for ( let i = 0 ; i < n ; i ++ ) { let temp = sum - arr [ i ] ; if ( temp % K == 0 ) { if ( res == - 1 mini > arr [ i ] ) { res = i + 1 ; mini = arr [ i ] ; } } } return res ; } let arr = [ 14 , 7 , 8 , 2 , 4 ] ; let K = 7 ; let N = arr . length ; document . write ( findIndex ( arr , N , K ) ) ;