Making elements of two arrays same with minimum increment / decrement | CPP program to find minimum increment / decrement operations to make array elements same . ; sorting both arrays in ascending order ; variable to store the final result ; After sorting both arrays Now each array is in non - decreasing order . Thus , we will now compare each element of the array and do the increment or decrement operation depending upon the value of array b [ ] . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinOperation ( int a [ ] , int b [ ] , int n ) { sort ( a , a + n ) ; sort ( b , b + n ) ; int result = 0 ; for ( int i = 0 ; i < n ; ++ i ) { result = result + abs ( a [ i ] - b [ i ] ) ; } return result ; } int main ( ) { int a [ ] = { 3 , 1 , 1 } ; int b [ ] = { 1 , 2 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << MinOperation ( a , b , n ) ; return 0 ; }