Given an array arr[] of size N, the task is to construct an array brr[] of size N that satisfies the following conditions:
- In every pair of consecutive elements in the array brr[], one element must be divisible by the other, i.e. brr[i] must be divisible by brr[i + 1] or vice-versa.
- Every ith element in the array brr[] must satisfy brr[i] >= arr[i] / 2.
- The sum of elements of the array arr[] must be greater than or equal to 2 * Σabs(arr[i] – brr[i]).
Examples:
Input: arr[] = { 11, 5, 7, 3, 2 }
Output: 8 4 4 2 2
Explanation:
abs(11 – 8) + abs(5 – 4) + abs(7 – 4) + abs(3 – 2) + abs(2 – 2) = 8
arr[0] + arr[1] + … + arr[4] = 28
2 * 8 <= 28 and for every ith element brr[i] >= arr[i] / 2.
Therefore, one of the possible values of brr[] are 8 4 4 2 2.Input: arr[] = { 11, 7, 5 }
Output: { 8, 4, 4 }
Approach: The idea is based on the following observation:
If brr[i] is the nearest power of 2 and is smaller than or equal to arr[i], then brr[i] must be greater than or equal to arr[i] / 2 and also the sum of elements of the array, arr[] must be greater than or equal to 2 * Σabs(arr[i] – brr[i]).
Follow the steps below to solve the problem:
- Initialize an array, brr[], to store the elements satisfying the given conditions.
- Traverse the array arr[]. For every ith element, find the nearest power of 2 which is smaller than or equal to arr[i] and store it in brr[i].
- Finally, print the array brr[].
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to construct an array // with given conditions void constructArray(int arr[], int N) { int brr[N] = { 0 }; // Traverse the array arr[] for (int i = 0; i < N; i++) { int K = log(arr[i]) / log(2); // Stores closest power of 2 // less than or equal to arr[i] int R = pow(2, K); // Stores R into brr[i] brr[i] = R; } // Print array elements for (int i = 0; i < N; i++) { cout << brr[i] << " "; } } // Driver Code int main() { // Given array int arr[] = { 11, 5, 7, 3, 2 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Function Call constructArray(arr, N); return 0; } |
8 4 4 2 2
Time Complexity: O(N)
Auxiliary Space: O(N)

