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.

Minimum number of Merge Operations to make an Array Palindrome in C

Algorithm :

  • 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

#include <stdio.h>

int MinOps(int arr[], int n)
{
int ans = 0;

for (int i=0,j=n-1; i<=j;)
{
if (arr[i] == arr[j])
{
i++;
j--;
}


else if (arr[i] > arr[j])
{
j--;
arr[j] += arr[j+1] ;
ans++;
}


else
{
i++;
arr[i] += arr[i-1];
ans++;
}
}

return ans;
}


int main()
{
int n;
scanf("%d", &n);

int arr[n];

for(int i=0; i<n; i++)
scanf("%d", &arr[i]);

printf("Count of minimum operations is %d", MinOps(arr, n));

return 0;
}
Output

5

1 2 3 1

1