- Arrays, Mathematical

Check if possible to make Array sum equal to Array product by replacing exactly one element

Given an array arr[] consisting of N non-negative integers, the task is to check if it is possible to make the sum of the array equal to the product of the array element by replacing exactly one array element with any non-negative integer.Examples:Input: arr[] = {1, 3, 4}Output: YesExplanation:Replacing the last element of the array with 2 modifies the array to {1, 3, 2}. The sum of array element  = 6 and  The product of array element is 1*2*3 = 6. Therefore, print Yes.Input: arr[] = {1, 2, 3}Output: NoApproach: The given problem can be solved by using the following mathematical observations:Consider the sum of array element as S and product of array element as P and after replacing any array element X with Y the sum and the product of array element must be the same, the equation becomes:=> S – X + Y = P * Y / X=> Y = (S – X) / (P / X – 1)From the above observations, the idea is to find the sum and the product of array elements as S and P and then iterate over the array element(say X) and find the value of Y using the above equation and if there exist any array element having the value of Y as a complete non-negative integer, then print Yes. Otherwise, print No.Below is the implementation of the above approach: Python3  def canPossibleReplacement(N, arr):          S = sum(arr)          P = 1      for i in arr:        P *= i              for x in arr:          y = (S-x)//(P / x-1)                  if (S-x + y) == (P * y)/x:              return ‘Yes’          return ‘No’    N, arr = 3, [1, 3, 4]print(canPossibleReplacement(N, arr))Output:
Time Complexity: O(N)Auxiliary Space: O(1)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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.