Wednesday, 27 Oct 2021

# Modify array to another given array by replacing array elements with the sum of the array

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 }Output: YESExplanation:Replacing input with (input + input + input) modifies input[] to { 1, 3, 1 }Replacing input with (input + input + input) modifies input[] to { 1, 3, 5 }Replacing input with (input + input + input) 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

Approach: The problem can be solved using Greedy technique. The idea is to always decrement the largest element of target[] array by the sum of the remaining array elements and check if the largest element of the target[]. If found to be true then print “YES”. Otherwise, print “NO”. Following are the observations:
If target[] = { 9, 3, 5 } and input[] = { 1, 1, 1 }Decrementing target by (target + target) modifies target[] to { 1, 3, 5 }Decrementing target by (target + target) modifies target[] to { 1, 3, 1 }Decrementing target by (target + target) modifies target[] to { 1, 1, 1 }Since input[] array and target[] equal, the required output is YES.

If the largest element in the array target[] is less than 1, then print “NO”.
If the largest element in the array target[] is equal to 1, then print “YES”.
Otherwise, decrement the largest element in the array target[] by the sum of remaining elements present in the array target[] while the largest element of the array is greater than 1.
Below is the implementation of the above approach:

Java

import java.io.*;
import java.util.*;

class GFG {

public static boolean isPossible(int[] target)
{

int max = 0;

int index = 0;

for (int i = 0; i < target.length; i++) {                                          if (max < target[i]) {                 max = target[i];                 index = i;             }         }                     if (max == 1)             return true;                     for (int i = 0; i < target.length; i++) {                                          if (i != index) {                                     max -= target[i];                                                      if (max