Given an list of positive integers of size N. We need to convert this list into palindromic list of maximum length. We can sum 2 consecutive elements to form a single element and the result obtained can be reused and this process can be repeated any no of times to convert it into palindromic list of maximum length.
Example :
Input : arr[]={10, 20, 30, 40, 50, 10}
Output : 5
Explanation :
compare first and last elements 10 == 10 both are equal count both the
terms now size=2;
20!=50 so add its adjacent element to 20 to make it 50
20+30 = 50 now size=4
40 will be middle term as no term left now size =5
given list becomes [10, 50, 40, 50, 10] of size 5
Input : arr[]={10, 20, 30, 40, 50, 30, 20, 10}
Output : 7
Explanation :
compare first and last elements 10 == 10 both are equal count both the
terms now size=2;
20==20 now size =4
30 == 30 now size =6
40!=50 there are no terms left except 40 and 50 so add them 90=40+50
and make it as middle element now size =7
given list becomes [10, 20, 30, 90, 30, 20, 10] of size 7
Approach :
Consider 2 pointers first one indicating starting index and second one to last index.
- if both are equal then increments the ans by 2
- if(arr[i]>arr[j]) then decrement j and add it with its consecutive element
- if(arr[i] < arr[j]) then increment i and add with its previous element
repeat step 1,2,3 until i<=j
Implementation :
//c++ implementation of
//above approach
#include <bits/stdc++.h>
using namespace std;
//function to calculate
//length of the palindromic
//list
int palindromiclist(int arr[],
int n)
{
//if length of list
//is 1 then that 1
//element is palindrome
if(n == 1)
return 1;
//to find palindrome
//take 2 pointers one
//is from start and other
//is from end of the array
//and compare them
//first pointer
int i = 0;
//end pointer
int j = n-1;
//store ans
int ans = 0;
while(i <= j)
{
//update answer by 1
//because as we reached
//mid element
if(i == j)
{
i++;
ans++;
}
//if both are equal
//then decrement last pointer
//and increment first pointer
//update answer by 2
else if(arr[i] == arr[j])
{
i++;
j--;
ans = ans +2;
}
//if arr[i] greater then arr[j]
//then decrement j and add
//its consecutive element
else if(arr[i] > arr[j])
{
j--;
arr[j] += arr[j+1];
}
//if(arr[i] less than arr[i]
//then increment i and add its
//consecutive element
else
{
i++;
arr[i] += arr[i-1];
}
}
return ans;
}
//driver code
int main() {
int n = 8;
int arr[n] = {10 ,20 ,30,
40 ,50 ,30,
20 ,10};
//function call
cout << palindromiclist(arr, n)
<< "\n";
return 0;
}
Time Complexity : O(N)
Space Complexity : O(1)