Hello I am making a code in C to find the value of the last sequence of palindromes of a specified size (d
) and I need to optimize this code as it is for an exercise platform called URI Online Judge and is giving Time Limit exceeded
.
https://www.urionlinejudge.com.br/judge/en/problems/view/1686
Given a string s[1..N], we define a palindromic sequence of length p and displacement d (1 <= p <= d) as a sequence of k (k >= 1) disjoint substrings of s (each of which is a palindrome of length p) distant d characters from each other.
More formally, it can be written as the following sequence of disjoint substrings of s : A= (s[i..i+p-1], s[i+d..i+d+p-1], s[i+2d..i+2d+p-1], ...), where each element of A is a palindrome of length p. Recall that a string is called a palindrome if it reads the same forwards and backwards.
The value of a palindromic sequence is the total number of characters from string s it uses (i.e., if the sequence has k palindromes of length p, its value is k*p). Given a fixed displacement value D, calculate the largest value of a palindromic sequence contained in a string S.
Input
Each test case is described using two lines. The first line contains two integers N and D (1 <= N <=10^5), 1 <= D <=10^5) representing respectively the length of the string S and the required displacement value. The next line contains the string S of length N consisting only of lowercase letters.The last test case is followed by a line containing two zeros.
Output
For each test case output a line with the maximum value of a palindromic sequence with displacement D in string S.Samples
Input
5 1
abbbc
Output
5
#include <stdio.h>
char palavra[100000];
int palindrome(const int inicio, const int fim) {
if (inicio >= fim) {
return 1;
}
if (palavra[inicio] != palavra[fim - 1]) {
return 0;
}
return palindrome(inicio + 1, fim - 1);
}
int maior_sequencia(const int n, const int d) {
int valor = 0, temp;
int i, j;
for (i = 1; i <= d; i++) {
temp = 0;
for (j = 0; j < n; j += d) {
if (palindrome(j, j + i)) {
temp++;
}
}
if (temp * i > valor) {
valor = temp * i;
}
}
return valor;
}
int main() {
int n, d;
while (1) {
scanf("%d %d", &n, &d);
if (n == 0 || d == 0) {
return 0;
}
scanf("%s", palavra);
printf("%d\n", maior_sequencia(n, d));
}
return 0;
}
edit: Now i have a functional code, but give Time Limit exceeded
again :/
edit 2: I added another version of the code, how could I optimize one of these two versions?
Time limit Exceeded
is just performance-related. \$\endgroup\$