Minimum prefix increments required to make all elements of an array multiples of another array | C ++ program for the above approach ; Function to find minimum count of operations required to make A [ i ] multiple of B [ i ] by incrementing prefix subarray ; Stores minimum count of operations required to make A [ i ] multiple of B [ i ] by incrementing prefix subarray ; Stores the carry ; Stores minimum difference of correspoinding element in prefix subarray ; Traverse the array ; Stores the closest greater or equal number to A [ i ] which is a multiple of B [ i ] ; Stores minimum difference ; Update totalOperations ; Update carry ; Driver Code ; Input arrays A [ ] and B [ ] ; Length of arrays
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumMoves ( int A [ ] , int B [ ] , int N ) { int totalOperations = 0 ; int carry = 0 ; int K = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { int nearestMultiple = ceil ( ( double ) ( A [ i ] + carry ) / ( double ) ( B [ i ] ) ) * B [ i ] ; K = nearestMultiple - ( A [ i ] + carry ) ; totalOperations += K ; carry += K ; } return totalOperations ; } int main ( ) { int A [ ] = { 3 , 4 , 5 , 2 , 5 , 5 , 9 } ; int B [ ] = { 1 , 1 , 9 , 6 , 3 , 8 , 7 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << MinimumMoves ( A , B , N ) << endl ; return 0 ; }