My issue
getting the correct output still it is saying it is wrong
My code
#include <stdio.h>
#include <string.h>
int main() {
int N, p = 0;
printf("Enter number of characters you want to enter in a string: ");
scanf("%d", &N);
getchar();
char str[N + 1];
printf("Enter characters (x for boy, y for girl): ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';
for (int i = 0; i < N - 1; i++) {
if (str[i] != str[i + 1]) {
p++;
}
}
printf("The maximum number of pairs: %d\n", p);
return 0;
}
Learning course: Greedy Algorithms
Problem Link: Chef and String Practice Problem in Greedy Algorithms - CodeChef
- You are printing unnecesarily stuff like:
printf("Enter number of characters you want to enter in a string: ");
Don’t do it.
- In the statement of the problem, it says:
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
However, you are using that T number as if it was the length of the string. It is not. The length of the string is not given to you.
You should have done something like this:
#include <stdio.h>
// This is given in the Constraints
const int N = 100000;
int main(void) {
// Test cases
int T;
scanf("%d", &T);
// Create a static string of max length.
char S[N];
while(T--){
scanf("%s", S);
// The length of the string is calculated this way
int StringLen = strlen(S);
int p = 0;
for(int i=0; i<(StringLen-1); i++){
if(S[i] != S[i+1]){
p++;
i++;
// Each time you find a pair, you should avoid count them again.
}
}
printf("%d\n",p);
}
return 0;
}