Open In App

Modify array to another given array by replacing array elements with the sum of the array | Set-2

Last Updated : 09 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an Array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step.

Examples:

Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 } 
Output: YES 
Explanation: 
Replacing input[1] with (input[0] + input[1] + input[2]) modifies input[] to { 1, 3, 1 } 
Replacing input[2] with (input[0] + input[1] + input[2]) modifies input[] to { 1, 3, 5 } 
Replacing input[0] with (input[0] + input[1] + input[2]) modifies input[] to { 9, 3, 5 } 
Since the array input[] equal to the target[] array, the required output is “YES”.

Input: input[] = { 1, 1, 1, 1 }, target[] = { 1, 1, 1, 2 } 
Output: NO

 

Naive Approach: The naive approach and the Greedy approach are already mentioned in Set-1 of this article.

Efficient Approach: The idea to solve the problem efficiently is based on the below intuition:

  • Instead of trying to check if target[] array can be reached, work backward and try to generate the array of 1s from the target[].
  • While working backward the maximum element of the array will be the sum of elements after the last turn. To keep track of the maximum element, use a max heap.
  • After every turn, remove the maximum element from the heap and determine the previous maximum element value. To do this find the sum of all elements of the array.

Follow the steps to solve the problem:

  • Create variables sum and lastSum to store the sum of all elements the sum of the array on previous step. 
  • To determine the previous element, find the difference of “sum” and “lastSum” from “lastSum”, i.e (lastSum – (sum – lastSum)).
  • Then put this value back to the heap and update the sum.
  • Continue this until either the sum is equal to one or the lastSum is equal to one.
  • In case, lastSum becomes less than sum or sum becomes equal to zero or the difference of lastSum and sum becomes zero, return false.

Below is the implementation of the above approach :

C++




// C++ code for the above approach:
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find if target[] can be reached
bool createTarget(vector<int>& target)
{
 
    // Initialise size of target array
    int n = target.size();
 
    // Initialise variable to store
    // sum of values
    int sum = 0;
 
    // Initialise variable to store
    // last sum
    int lastSum;
 
    // Initialise a max-heap to keep track
    // of the maximum element
    priority_queue<int> maxHeap(target.begin(),
                                target.end());
 
    // Start traversing to find the sum
    for (int i = 0; i < n; i++) {
        sum = sum + target[i];
    }
 
    // While heap has element traverse
    while (true) {
 
        // Update last sum with
        // maximum value of heap
        lastSum = maxHeap.top();
 
        // Pop the maximum element
        // of the heap
        maxHeap.pop();
 
        // Update sum of values
        sum = sum - lastSum;
 
        // If either sum or last sum is
        // equal to 1, then
        // target array possible
        if (lastSum == 1 || sum == 1) {
 
            // Return true
            return true;
        }
 
        // If last sum becomes less than
        // sum or if sum becomes equal
        // to 0 or if difference of last
        // sum and sum becomes 0
        if (lastSum < sum || sum == 0
            || lastSum - sum == 0) {
 
            // Return false
            return false;
        }
 
        // Update last sum
        lastSum = lastSum - sum;
 
        // Update sum
        sum = sum + lastSum;
 
        // Push last sum into the queue
        maxHeap.push(lastSum);
    }
}
 
// Driver code
int main()
{
    int N = 2;
    vector<int> target = { 2, 3 };
    bool ans = createTarget(target);
    if (ans)
        cout << "YES";
    else
        cout << "NO";
    return 0;
}


Java




// Java code for the above approach:
import java.util.*;
 
// Function to find if target[] can be reached
class GFG {
  static boolean createTarget(int[] target)
  {
     
    // Initialise size of target array
    int n = target.length;
 
    // Initialise variable to store
    // sum of values
    int sum = 0;
     
    // Initialise variable to store
    // last sum
    int lastSum = 0;
 
    // Initialise a max-heap to keep track
    // of the maximum element
    PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>();
    for (int i = 0; i < target.length; i++)  
       
      // we are using negative values as we want to remove the maximum element
      // from the priority queue, however, by default the minimum element i removed using poll()
      maxHeap.add(-1 * target[i]);
 
    // Start traversing to find the sum
    for (int i = 0; i < n; i++)
      sum += target[i];
     
    // While heap has element traverse
    while (true)
    {
       
      // Update last sum with
      // maximum value of heap and also
      //remove the maximum value from heap
      lastSum = -1 * maxHeap.poll();
       
      // Update sum of values
      sum -= lastSum;
       
      // If either sum or last sum is
      // equal to 1, then
      // target array possible
      if (lastSum == 1 || sum == 1)
      {
        return true;
      }
       
      // If last sum becomes less than
      // sum or if sum becomes equal
      // to 0 or if difference of last
      // sum and sum becomes 0
      if (lastSum <= sum || sum == 0 )
      {
        return false;
      }
       
      // update lastsum and sum
      lastSum = lastSum - sum;
      sum += lastSum;
       
      // Push last sum into the queue
      maxHeap.add(-1 * lastSum);
    }
  }
 
  // Driver code
  public static void main(String[] args) {
    int N = 2;
    int[] target = {2, 3};
    boolean ans = createTarget(target);
    if (ans)
      System.out.println("YES");
    else
      System.out.println("NO");
  }
}
 
// This code is contributed by phasing17


Python3




# python3 code for the above approach:
from queue import PriorityQueue
 
# Function to find if target[] can be reached
def createTarget(target):
 
    # Initialise size of target array
    n = len(target)
 
    # Initialise variable to store
    # sum of values
    sum = 0
 
    # Initialise variable to store
    # last sum
    lastSum = 0
 
    # Initialise a max-heap to keep track
    # of the maximum element
    maxHeap = PriorityQueue()
 
    for itm in target:
        maxHeap.put(-itm)
 
        # Start traversing to find the sum
    for i in range(0, n):
        sum = sum + target[i]
 
        # While heap has element traverse
    while True:
 
                # Update last sum with
                # maximum value of heap
        lastSum = -maxHeap.get()
 
        # Pop the maximum element
        # of the heap
 
        # Update sum of values
        sum = sum - lastSum
 
        # If either sum or last sum is
        # equal to 1, then
        # target array possible
        if (lastSum == 1 or sum == 1):
 
                        # Return true
            return True
 
            # If last sum becomes less than
            # sum or if sum becomes equal
            # to 0 or if difference of last
            # sum and sum becomes 0
        if (lastSum < sum or sum == 0
                or lastSum - sum == 0):
 
                        # Return false
            return False
 
            # Update last sum
        lastSum = lastSum - sum
 
        # Update sum
        sum = sum + lastSum
 
        # Push last sum into the queue
        maxHeap.put(-lastSum)
 
# Driver code
if __name__ == "__main__":
 
    N = 2
    target = [2, 3]
    ans = createTarget(target)
    if (ans):
        print("YES")
    else:
        print("NO")
 
    # This code is contributed by rakeshsahni


C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
  static bool createTarget(int[] target)
  {
 
    // Initialise size of target array
    int n = target.Length;
 
    // Initialise variable to store
    // sum of values
    int sum = 0;
 
    // Initialise variable to store
    // last sum
    int lastSum = 0;
 
    // Initialise a max-heap to keep track
    // of the maximum element
    List<int> maxHeap = new List<int>();
    for (int i = 0; i < target.Length; i++)  
 
      // we are using negative values as we want to remove the maximum element
      // from the priority queue, however, by default the minimum element i removed using poll()
      maxHeap.Add(-1 * target[i]);
 
    // Start traversing to find the sum
    for (int i = 0; i < n; i++)
      sum += target[i];
 
    // While heap has element traverse
    while (true)
    {
 
      // Update last sum with
      // maximum value of heap and also
      //remove the maximum value from heap
 
      // Update last sum with
      // maximum value of heap
      lastSum = maxHeap[0];
 
      // Pop the maximum element
      // of the heap
      maxHeap.RemoveAt(0);
 
 
      // Update sum of values
      sum -= lastSum;
 
      // If either sum or last sum is
      // equal to 1, then
      // target array possible
      if (lastSum == 1 || sum == 1)
      {
        return true;
      }
 
      // If last sum becomes less than
      // sum or if sum becomes equal
      // to 0 or if difference of last
      // sum and sum becomes 0
      if (lastSum <= sum || sum == 0 )
      {
        return false;
      }
 
      // update lastsum and sum
      lastSum = lastSum - sum;
      sum += lastSum;
 
      // Push last sum into the queue
      maxHeap.Add(-1 * lastSum);
    }
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 2;
    int[] target = {2, 3};
    bool ans = createTarget(target);
    if (ans == false)
      Console.Write("YES");
    else
      Console.Write("NO");
  }
}
 
// This code is contributed by sanjoy_62.


Javascript




// JavaScript program to implement
// the above approach
function createTarget(target)
{
 
    // Initialise size of target array
    var n = target.length;
 
    // Initialise variable to store
    // sum of values
    var sum = 0;
 
    // Initialise variable to store
    // last sum
    var lastSum = 0;
 
    // Initialise a max-heap to keep track
    // of the maximum element
    maxHeap = [];
    for (var i = 0; i < target.length; i++)
 
        // we are using negative values as we want to remove
        // the maximum element from the priority queue,
        // however, by default the minimum element i removed
        // using poll()
        maxHeap.push(-1 * target[i]);
 
    // Start traversing to find the sum
    for (var i = 0; i < n; i++)
        sum += target[i];
 
    // While heap has element traverse
    while (true) {
 
        // Update last sum with
        // maximum value of heap and also
        // remove the maximum value from heap
 
        // Update last sum with
        // maximum value of heap
        lastSum = maxHeap[0];
 
        // Pop the maximum element
        // of the heap
        maxHeap.splice(0, 1);
 
        // Update sum of values
        sum -= lastSum;
 
        // If either sum or last sum is
        // equal to 1, then
        // target array possible
        if (lastSum == 1 || sum == 1) {
            return true;
        }
 
        // If last sum becomes less than
        // sum or if sum becomes equal
        // to 0 or if difference of last
        // sum and sum becomes 0
        if (lastSum <= sum || sum == 0) {
            return false;
        }
 
        // update lastsum and sum
        lastSum = lastSum - sum;
        sum += lastSum;
 
        // Push last sum into the queue
        maxHeap.pushh(-1 * lastSum);
    }
}
 
// Driver Code
var N = 2;
var target = [ 2, 3 ];
var ans = createTarget(target);
if (ans == false)
    console.log("YES");
else
    console.log("NO");
     
// This code is contributed by  phasing17


Output

true

Time Complexity: O(N * log(N) + (K / N * log(N))), where K is the maximum element of the array.
Auxiliary Space: O(N)



Similar Reads

Modify array to another given array by replacing array elements with the sum of the array
Given an array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 }
13 min read
Modify string by replacing all occurrences of given characters by specified replacing characters
Given a string S consisting of N lowercase alphabets and an array of pairs of characters P[][2], the task is to modify the given string S by replacing all occurrences of character P[i][0] with character P[i][1]. Examples: Input: S = "aabbgg", P[][2] = {{a, b}, {b, g}, {g, a}}Output: bbggaaExplanation:Replace 'a' by 'b' in the original string. Now t
12 min read
Modify a given array by replacing each element with the sum or product of their digits based on a given condition
Given an array arr[] consisting of N integers, the task is to modify the array elements after performing only one of the following operations on each array elements: If the count of even digits is greater than the count of odd digits in an array element, then update that element to the sum of all the digits of that element.Otherwise, update that el
8 min read
Modify array by replacing elements with their farthest co-prime number from a given range
Given an array arr[] consisting of N integers and two positive integers L and R, the task is to find the farthest co-prime number in the range [L, R] for every array element. Examples: Input: arr[] = {5, 150, 120}, L = 2, R = 250Output: 249 7 247Explanation:The number which is co-prime with arr[0] and farthest from it is 249.The number which is co-
7 min read
Modify array by replacing elements with the nearest power of its previous or next element
Given a circular array arr[] consisting of N positive integers, the task is to modify the array by replacing each array element with the nearest power of its previous or next array element. Examples: Input: arr[] = {2, 3, 4, 1, 2}Output: {2, 4, 3, 1, 2}Explanation:For arr[0](= 2): The previous and the next array elements are 2 and 3 respectively. T
8 min read
Modify array by replacing each element with nearest power of GCD of all previous elements
Given an array arr[] consisting of N positive integers, the task is to replace each array element with the nearest power of GCD of all the preceding array elements. If there exists more than one possible answer, then print any one of them. Examples: Input: arr[] = {4, 2, 8, 2}Output: 4 1 8 2Explanation: For element arr[0], the element remains the s
9 min read
Maximize product of array by replacing array elements with its sum or product with element from another array
Given two arrays A[] and B[] consisting of N integers, the task is to update array A[] by assigning every array element A[i] to a single element B[j] and update A[i] to A[i] + B[j] or A[i] * B[j], such that the product of the array A[] is maximized. Note: Every array element in both the arrays can be paired with a single element from the other arra
7 min read
Modify a matrix by replacing each element with the maximum of its left or right diagonal sum
Given a matrix mat[][] with dimensions M * N, the task is to replace each matrix elements with the maximum sum of its left or right diagonal. Examples: Input: mat[][] = {{5, 2, 1}, {7, 2, 6}, {3, 1, 9}}Output: 16 9 6 9 16 86 8 16Explanation:Replace each element with max(sum of right diagonal, sum of left diagonal).Follow the diagram below to unders
7 min read
Modify Binary Tree by replacing each node with the sum of its Preorder Predecessor and Successor
Given a binary tree consisting of N nodes, the task is to replace each node in the binary tree with the sum of its preorder predecessor and preorder successor. Examples: Input: 2 / \ 3 4 / \ / \ 6 5 7 8 Output: 3 / \ 8 12 / \ / \ 8 10 12 7 Explanation: For Node 2: Preorder predecessor = 0 (as preorder predecessor is not present), preorder successor
13 min read
Modify sequence of first N natural numbers to a given array by replacing pairs with their GCD
Given an integer N and an array arr[], the task is to check if a sequence of first N natural numbers, i.e. {1, 2, 3, .. N} can be made equal to arr[] by choosing any pair (i, j) from the sequence and replacing both i and j by GCD of i and j. If possible, then print "Yes". Otherwise, print "No". Examples: Input: N = 4, arr[] = {1, 2, 3, 2}Output: Ye
11 min read