Find Array After Inserting New Elements with Difference in C++



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 < n, update (increase i by 1), do:
   a := A[i]
   if a < 0, then:
      t := 1
   b := maximum of a and b
if t is non-zero, then:
   print -1
Otherwise
   for initialize i := 0, when i <= b, update (increase i by 1), do:
      print i

Example

Let us see the following implementation to get better understanding −

Open Compiler
#include <bits/stdc++.h> using namespace std; void solve(vector<int> A) { int n = A.size(); int t = 0; int b = 0; for (int i = 0; i < n; i++) { int a = A[i]; if (a < 0) t = 1; b = max(a, b); } if (t) cout << "-1"; else { for (int i = 0; i <= b; i++) cout << i << ", "; } } int main() { vector<int> 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

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements