Home > database >  Length of a growing substring in matrix
Length of a growing substring in matrix

Time:12-10

Given a square matrix find the length of sub string that is growing for example.

matrix     |      result       because of
5          |
1 2 3 4 5  |
2 5 2 5 9  |    
7 8 9 0 1 -->       5     -->   1 2 3 4 5
0 0 0 0 0  |
2 3 6 1 2  |

I try to compare a[i][j] with a[i][j 1] and increment the counter but I think my problem is when the program is on the final elements and it does not increment the counter. Here I have my code:

int main(){
    int n;
    scanf("%d",&n);
    int i,j,a[n][n];
    for(i = 0;i < n;i  ){
        for(j = 0;j <n;j  ){
            scanf("%d",&a[i][j]);
        }
    }
    int max=-9999;
    int counter;
    for(i = 0;i < n;i  ){
        counter=0;
        for(j = 0;j <n;j  ){
            if(a[i][j]<a[i][j 1]){
                counter  ;
            }
            if(counter>max){
                max = counter;
            }
        }
    }
    printf("%d",max);
    return 0;
}

CodePudding user response:

For starters as the range of indices can not be negative then there is no sense to declare the variable max as having a negative value

int max=-9999;

It could be initialized at least like

int max = 0;

In this if statement

if(a[i][j]<a[i][j 1]){

there can be an access to memory beyond the allocated array when i and j are equal to n - 1 due to the expression a[i][j 1].

Also this if statement

        if(counter>max){
            max = counter;
        }

should be moved outside the inner if statement.

And the variable count should be declared inside the outer loop

You could rewrite the inner for loop the following way

    int counter=1;
    for(j = 1;j <n;j  ){
        if(a[i][j-1]<a[i][j]){
            counter  ;
        }
    }
    if(counter>max){
        max = counter;
    }
  • Related