The Wayback Machine - https://web.archive.org/web/20210118092729/https://www.geeksforgeeks.org/generate-an-n-length-array-with-sum-equal-to-twice-the-sum-of-its-absolute-difference-with-same-indexed-elements-of-given-array/
Related Articles

Related Articles

Generate an N-length array with sum equal to twice the sum of its absolute difference with same-indexed elements of given array
  • Last Updated : 17 Jan, 2021

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:

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

8 4 4 2 2

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :