Minimum number of Merge Operations to make an Array Palindrome in C
Minimum number of merge operations
Here, in this section we discuss code for finding minimum number of merge operations to make array palindrome.
We are given with an array of positive integers. If array is not a palindrome, make merge operations and prints the number of merge operations. In each merge operation it will merge two adjacent elements. Here, merging two elements means replacing them with their sum.
A palindrome is a word, phrase, or sequence that reads the same backwards as forwards.
- Take the size of array from the user and store it in variable named n.
- Declare an array of size n and take n integer values from the user.
- Create two variables i,j. i will point to the start of the array and j to the end.
- Run a loop till i less then or equal to j.
- If arr[i] = arr[j], then there is no need to merge the elements. Increment i and decrement j
- If arr[i] > arr[j], then do merge operation at index j ie, arr[j-1] = arr[j-1] + arr[j], decrement j and increment the no of merge operations count by 1
- If arr[i] < arr[j], then do merge operation at index i ie, arr[i+1] = arr[i+1] + arr[i], increment i and increment the no of merge operations count by 1
Code in C, based on above algorithm
int MinOps(int arr, int n)
int ans = 0;
for (int i=0,j=n-1; i<=j;)
if (arr[i] == arr[j])
else if (arr[i] > arr[j])
arr[j] += arr[j+1] ;
arr[i] += arr[i-1];
for(int i=0; i<n; i++)
printf("Count of minimum operations is %d", MinOps(arr, n));
1 2 3 1