Given an array A of size N. Find the minimum number of operations needed to convert the given array to Palindromic Array
belongs to collection: Interview C++ coding problems/challenges | arrays
All Answers
total answers (1)
belongs to collection: Interview C++ coding problems/challenges | arrays
total answers (1)
Algorithm:
For solving the above problem a recursive algorithm can be constructed based on the following conditions.
Let array [i, j] be the subarray to be checked where I be the staring index & j be the end index
So there can be three cases,
Based on these three conditions we have constructed the recursive function:
findNoOfOperation(input array, starting index, ending index) Let, i=start index j=end index FUNCTION findNoOfOperation(input array, i, j) BASE CASE IF(i==j) return 0; //no more operations needed END IF IF (i<=j) IF(a[i]==a[j]) No of operations needed for array(i, j) is same as array(i+1, j-1) return findNoOfOperation (array,i+1,j-1);//recursive call ELSEIF(a[i]>a[j]) We need to merge the two element at the end to convert it into palindrome array array [j-1]=array[j]+array[j-1]; //merge No of operations needed for array(i, j) is one more than array(i, j-1) return findNoOfOperation(array,i,j-1)+1; ELSE We need to merge the two element at the start to convert it into palindrome array array[i+1]=array[i]+array[i+1]; No of operations needed for array(i, j) is one more than array(i+1, j) returnfindNoOfOperation(array,i+1,j)+1; END IF-ELSE END IF END FUNCTIONExample with explanation:
C++ implementation:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer