C++ program to find array after inserting new elements where any two elements difference is in array

Suppose we have an array A with n distinct elements. An array B is called nice if for any two distinct elements B[i] and B[j], the |B[i] - B[j]| appears in B at least once, and all elements in B will be distinct. We have to check whether we can add several integers in A to make it nice of size at most 300. If possible return the new array, otherwise return -1.

So, if the input is like A = [4, 8, 12, 6], then the output will be [8, 12, 6, 2, 4, 10], because |4−2| = |6−4| = |8−6| = |10−8| = |12−10| = 2 is in the array, |6−2| = |8−4| = |10−6| = |12−8| = 4 is in the array, |8−2| = |10−4| = |12−6| = 6 is in the array, |10−2| = |12−4| = 8 is in the array, and |12−2| = 10 is in the array, so the array is nice. (Other answers are also possible)

Steps

To solve this, we will follow these steps −

n := size of A
t := 0
b := 0
for initialize i := 0, when i 

Example

Let us see the following implementation to get better understanding −

#include 
using namespace std;

void solve(vector A) {
   int n = A.size();
   int t = 0;
   int b = 0;
   for (int i = 0; i  A = { 4, 8, 12, 6 };
   solve(A);
}

Input

{ 4, 8, 12, 6 }

Output

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
Updated on: 2022-03-03T10:05:15+05:30

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements