Smallest possible integer to be added to N | C ++ program for the above approach ; Function to find the smallest positive integer X such that X is added to every element of A except one element to give array B ; Stores the unique elements of array A ; Insert A [ i ] into the set s ; Sort array A [ ] ; Sort array B [ ] ; Assume X value as B [ 0 ] - A [ 1 ] ; Check if X value assumed is negative or 0 ; Update the X value to B [ 0 ] - A [ 0 ] ; If assumed value is wrong ; Update X value ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findVal ( int A [ ] , int B [ ] , int N ) { unordered_set < int > s ; for ( int i = 0 ; i < N ; i ++ ) { s . insert ( A [ i ] ) ; } sort ( A , A + N ) ; sort ( B , B + N - 1 ) ; int X = B [ 0 ] - A [ 1 ] ; if ( X <= 0 ) X = B [ 0 ] - A [ 0 ] ; else { for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( s . count ( B [ i ] - X ) == 0 ) { X = B [ 0 ] - A [ 0 ] ; break ; } } } cout << X << endl ; } int main ( ) { int A [ ] = { 1 , 4 , 3 , 8 } ; int B [ ] = { 15 , 8 , 11 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; findVal ( A , B , N ) ; return 0 ; }