0

Print the largest (maximum) hourglass sum found in arr :

-1 -1  0 -9 -2 -2
-2 -1 -6 -8 -2 -5
-1 -1 -1 -2 -3 -4
-1 -9 -2 -4 -4 -5
-7 -3 -3 -2 -9 -9
-1 -3 -1 -2 -4 -5
int hourglassSum(int arr_rows, int arr_columns, int** arr) {
    int max=0;
    int i,j;
    for(i=0;i<arr_rows-2;i++){
        for(j=0;j<arr_columns-2;j++){
          int sum=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];
           if(sum>=max){
               max=sum;
           }
        }   
    }
    return max;
}

the answer should be -6 but I got 0 why is this happen ?

Antutu Cat
  • 105
  • 4

1 Answers1

1

Two problems :

Firstly, max is set to 0 (int max=0) , all sums are negatives, therefore 0 is always greater.

Secondly, see How to pass 2D array (matrix) in a function in C? to understand how to pass 2D array to a function.

(Example of code but others solutions are possible. I suppose your compiler supports VLA. Let me know if it is not the case. I have another solution)

#include <math.h> // To have the definition of INFINITY

int hourglassSum(int arr_rows, int arr_columns, int arr[arr_rows][arr_columns]) { //For compiler that supports VLA
    int max=-INFINITY;
    int i,j;
    for(i=0;i<arr_rows-2;i++){
        for(j=0;j<arr_columns-2;j++){
          int sum=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];
          printf("sum %d\n",sum);
           if(sum>=max){
               max=sum;
           }
        }
    }
    return max;
}

And to call it : hourglassSum(6,6,a)

Stef1611
  • 1,978
  • 2
  • 11
  • 30