Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Length of a growing substring in matrix

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading