If you only want the solution to the easy version of the problem, here it is:
Initialize an array prefix[27][N]
What does the array store?
It is said in the problem that maximum value of a[i] can be 26.
Thus,
prefix[i][j] stores the number of occurences of the i th from position 1 to position j in the input array.
We have variable maxans as the maximum answer. As in the 3 block palindrome, a and b can be the same, thus, the following code can be implemented when a and b are the same:
Code which can be implemented
//Code when a and b are the same
const long long N = 2010;
long long prefix[27][N]; //this array stores the same which is mentioned above
long long Same(long long n) { //the argument which this function takes is the same as input given of n
long long max_ans = 0;
for(long long i = 1; i <= 26; i++) {
max_ans = max(max_ans, prefix[i][n - 1]); //prefix[i][n - 1] stores the occurence of the ith element in the whole array
}
return max_ans;
}
Now, what to do when a and b are different?
Lets take a block l to r which contains b. This is our second block. Thus, the first block here is from 1 to l - 1, and the third block is from r + 1 to n
It is something like this:
1.....l - 1 | l.....r | r + 1.....n
Thus, for any l and r, go through all the elements in the array,
i.e from 1 to 26 and find the maximum occurrence of that element.
Now we have the maximum occurrence of that element. Run another loop and then find the occurrences of that element from
1 to l - 1 and r + 1 to n.
Let this be called maxoccurrence.
Thus maxans = max(maxans, maxoccurrence)
Code to be Implemented
```//Code to be implemented when a and b are same or different
const long long N = 2010;
long long prefix[27][N];
long long SolveProblem(long long n) {
long long max_ans = 0;
for(long long left = 1; left <= n; left++) {
for(long long right = left; right <= n; right++) {
long long temp = 0, temp1 = 0; //these stores the occurrence of the character in the second block, and the first and third block respectively
//1...left - 1 is first block
//left...right is second block
//right + 1...n is third block
for(long long i = 1; i <= 26; i++) {
temp = max(temp, prefix[i][right] - prefix[i][left - 1]);
}
for(long long j = 1; j <= 26; j++) { //noticed how I merged the "Same" function which will be implemented itself when i and j will be equal
temp1 = max(temp1, prefix[j][left - 1] + (prefix[j][n] - prefix[j][right]));
}
max_ans = max(max_ans, temp + temp1);
}
}
return max_ans;
}
int main() {
/* input and other stuff to be done here*/
cout << SolveProblem(n) << endl;
}
Hope you understood
. If you want to understand the harder version, or ask doubts leave a reply to this comment, and I will get back to you asap. 