- Practice
- Data Structures
- Arrays
- 2D Array - DS
- Discussions

# 2D Array - DS

# 2D Array - DS

thegeeksam + 60 comments if you want to pass test Case 3 and 5 dont initialize max value to 0.

madulidjpAsked to answer + 16 comments yeah. you should initialize the max value to the value of the first hourglass.

ronak319 + 52 comments you can also set any large negative value also. Then no need to caluculate first hourglass separately.

for e.g , max_value = -99999;

ivdekov + 6 comments This is helpful, thank you. I used Integer.MIN_VALUE;

ldaicich + 7 comments Just a very silly thing, but you can also use Short values for the purpose of this problem, it doesn't have to be necessarily an Integer. Just for using less memory. :)

bin_zhao10 + 1 comment I think the input variables are defined as primitive type int.

ocalderon + 0 comments But that doesn't mean you cannot change. At the end the output is a string, so it doesn't matter.

abhilashupare + 4 comments Guys we also have one more alternative, with the help of flag we can achieve it,

if (flag) {

max = sum;

flag = false;

}

if (max < sum) {

max = sum;

}

mdmoniskhan + 0 comments will it not give a compilation error i.e max is not initialized or something like that?

canpy30 + 1 comment or in JS:

let max;

if (typeof max !== 'number' || sum > max) { max = sum }

Raullg98 + 1 comment I used, max = -Infinity

kanishk_vishwa21 + 1 comment Very large negative values are not necessary. See that an hourglass is made up of 7 digits. the sum of 'those' 7 digits can be minimum when each digit is itself minimum, i.e, -9. Hence, the minimum sum will be (7)x(-9), which equals -63. So, we can initialize minimum as -64

dani7603 + 1 comment you could actually initialize it with -63 ,would still work.

Bulgogi_Wan + 0 comments In JS, I used

let maxSum = Number.MIN_SAFE_INTEGER;

ahamedkabeer279 + 0 comments beautiifull logic

lianyuu + 0 comments you can just set the initilize max value as the last hourglass

successhawk + 1 comment Using your logic, you could use the type byte.

happyoutdoors + 0 comments In Java you could use byte, since it is signed. In C# byte is an unsigned type and not appropriate.

To store the numbers you really only need 7 bits, but there's little use in packing these arrays.

TechieToby + 2 comments Given the constraint in the question (-9 <= arr[i][j] <= 9 and 0 <= i,j <= 5), I used the possible maximum negative value to initialize my max value (-9 * 6 = -54).

sammurphych + 5 comments max negative value is -63 (-9 * 7)

amanagarwal2189 + 1 comment anything less than -54.

ghaderi_amin + 2 comments For python initialize with: -9223372036854775807

sanyal_parnab96 + 0 comments I initialized with 1 << 16 * -1

happyoutdoors + 0 comments That would very silly. Why not just use the minimum value of -63 as others have indicated.

steve_o + 0 comments This is correct, but the test cases given also had nothing lower than -54, which was lucky for me, since I made the (mindless) error of thinking there were only 6 elements in an hourglass.

One of the test cases should have a max of -62 for this reason, IMO.

sean_novick + 0 comments This is correct. Given the question the lowest possible sum is -63. The sum of an hourglass is always multiplied by 7 (2 rows of 3 + 1 column of 1). The highest negative number is -9. Therefore -9 * 7 = -63

floreat_bangoria + 0 comments first value always works and doesn't rely on you knowing the input before execution

ignacioja + 0 comments I did the same :), 7 number and values between -9 and 9, so doing the maths. highest negative is -63 and highest positive 63. Because you need the lowest asume value, you choose -63.

vineeth_1999 + 0 comments yes intitalizing max value less than maximum negative value helped me in solving 3,5,7 testcases

kanishk_vishwa21 + 0 comments Very large negative values are not necessary. See that an hourglass is made up of 7 digits. the sum of 'those' 7 digits can be minimum when each digit is itself minimum, i.e, -9. Hence, the minimum sum will be (7)x(-9), which equals -63. So, we can initialize minimum as -64.

rishabh10 + 0 comments as a[i][j]>=-9 so just initialize the min value to -9*7 as hour glass consiste of 7 elements and considering worst case for least sum all would be -9

tarun_77870 + 0 comments Well if you will analyze inuts then you will get the idea. no array value can be < -9. it means [(-9 *3 *2)+-(9)] . this is your lowest value

mudit2jain + 2 comments It passed the testcases but why it doesn't runs when initialized to zero?

prajapple + 4 comments If the sums of hourglasses are all negative , and if u have taken your max variable initilized to zero and calculate the max with refrence to 0 obviously you will be returning 0 as the answer which is wrong . So its better to initilize with Integer.MIN_VALUE to a variable to which will be storing a max value .

kapil18pandey + 1 comment thanks mate... helped a lot!!!

balajilitsv + 1 comment Or initialize it to any value less than -63, because the input values of the array ranges from -9 to +9. So a hour glass can contain a maximum of 7 times -9, which sums up to -63. Any value greater than -64 can be accepted to swap the max variable, right!

**HotIce!**Try this man!1l0v3c0d3 + 0 comments Actually, -63 will work too.

balajilitsv + 0 comments Or initialize it to any value less than -63, because the input values of the array ranges from -9 to +9. So a hour glass can contain a maximum of 7 times -9, which sums up to -63. Any value greater than -64 can be accepted to swap the max variable, right!

**HotIce!**VishalVasistha + 0 comments Taking max value as integer.MIN_VALUE is also correct however max can also be sumArray[0] (the array of sum of hourglasses) .

jaismeenkaur + 1 comment Thanks ! That helped.

mohitmude19 + 0 comments It is given that minimum value of array element is -9. So, minimum sum could be -63(i.e -9*7).

tfloresu + 1 comment Zero is considered to be a positive number. If all the hour glasse's totals are negative they wont beat your zero.

happyoutdoors + 0 comments Even if some of them are zero they won't beat that zero.

pratikkejriwal + 0 comments instead of using min value of integer, you can just initialize it to -63 as it is clearly mentioned that the values cannot be less than -9. So -9*7=-63

mostafakerim30 + 1 comment I made two iterations: First time to find the lowest value and the second time to calculate the highest value starting at the lowest value.

happyoutdoors + 0 comments That is extremely inefficient since it is not necessary to know the lowest value just to initialize your maximum value variable.

ahmadmoussawi + 0 comments Actually it shoud be the smallest number possible where all values are equals to -9 => -9*7 = -63

SONIT + 0 comments You could also keep -63. Because minimum hourglass sum possible is -63.

mondayrain + 4 comments It's worth noting that the description clearly states that the input will be -9 <= R <= 9. This means that the smallest possible value will be -9*7 (as there are 7 elements in an hourglass). So one can just initialize the max value to -63 :)

Eschatite + 0 comments [deleted]aman1324 + 0 comments Yes. In case the constraints are not there, use Integer.MIN_VALUE.

anuragpugalia11 + 0 comments yes it worked. thanks

architvis + 0 comments This is were I messed up, I initialized max value to -9. Thanks, didn't relize were I messed up at until reading your comment.

kaasib + 1 comment Simply set it to null and use type specific comparison to assign first sum.

anshulkataria4 + 1 comment why do we need to set max to -63 or to any such value ?

t_egginton + 1 comment because if you initialise to zero, if the max hourglass sum is negative then it will not overwrite the zero value. best to either initialise it with the value of the first hourglass (slightly more elegent in my opinion) or a large negative value. 63 is significant because it is not possible to get a sum less than that under the constraints given.

nancy345 + 1 comment hello sir! i want to know that if we want to do this programming in c so what programe is used from the starting because my basic in c and c++ is not clear and also i m not familiar with its operation so kindly send me a complete programe based on it in C. thanku

mdumlupinar + 0 comments [deleted]

amulya_123 + 2 comments why should we initialize max value to large negative value?

supertrens + 0 comments because if you initialise to zero, if the max hourglass sum is negative then it will not overwrite the zero value. since 0 will be greater to any negative number. What I do is save the first hourglass sum as teh finalSum and update it when/if the next ones are bigger.

sugsurnitsin + 0 comments what is the hour glass

ernestns + 0 comments [deleted]shrewga + 1 comment The least no. possible is -9 * 7 = -63. We can also initialize it to that. :)

meerakrish + 1 comment Thanks

shrewga + 0 comments [deleted]

varun_1995 + 0 comments int max = Integer.MIN_VALUE;

abhiram_n + 0 comments actually -63 is enough.Since 7 slots having a minimum value of -9 in each would turn out to a maximum negative of -7*9=-63

gmoralesc + 0 comments I used Number.NEGATIVE_INFINITY with Javascript

nikhil_j_kurien + 0 comments you can set it to integer.MIN_VALUE

GomathiN + 0 comments You can use -63 as max value because it is stated in condition that a[i][j] is between -9 and + 9

vamsi5 + 0 comments you know max_value = -63 would do just fine. because the lowest maximum number that can be achieved with given constraints is -63. The given constraints for element in array is [-9,9] so the max an hour glass with all -9s would give (-9)*(7(no_of elements in hour glass)) = -63

sangeetharaj + 1 comment may i know what is the reason behind this? why we have to initiliza ma_value = -9999 or -63

samuelpaulc + 0 comments since the hourglass with smallest sum is -63 when all values in hourglass are -9

nithindevn + 0 comments [deleted]shiva_nk + 0 comments -63 would be enough

deepak111224 + 0 comments bro you can just set max value to -9 * 7 = -63 cause it can be the most small value of hourglass acording to question

chaudharymayank1 + 0 comments even -63 can work fine

alex_wallish + 0 comments No need to set max value that low. It will not possibly be any lower than 7*9 so you can simply initialize it to 63.

david_rodriguez2 + 0 comments perhaps -9*7 is enough, though

harminder_oassan + 0 comments you could just use one less than the minimum possible value of an hourglass, which is -64.

balajilitsv + 0 comments Or initialize it to any value less than -63, because the input values of the array ranges from -9 to +9. So a hour glass can contain a maximum of 7 times -9, which sums up to -63. Any value greater than -64 can be accepted to swap the max variable, right!

**HotIce!**mosjabr + 0 comments since the least sum is -63 (when all elements are -9), you can initialize it to be -63

_withoutwax + 1 comment Or you can use

float('-inf')

which gives you the largest negative value.

ghaderi_amin + 0 comments Worked like a charm. Thanks. I didnt know we can compare floats and integers.

dv1pr + 0 comments I set max = nil and then checked if max was nil before setting max to the total with an or conditional

e.g., max = total if max == nil || total > max

aaliagab85 + 0 comments short mayor=-63;

edward_cerveriz1 + 0 comments If you are writing in Java, you can actually use max_value= Integer.MIN_VALUE; to get the lowest signed interger value in case -99999 isn't enough.

jordancg91 + 0 comments The problem specifies that arr[i][j] values are only between -9 and 9, so the minSum for any hourglass can be -63, specifing the initial max_value = -64 will ensure that any sum will be greater

tpnewhistory + 0 comments Actually, since the constraint is -9, and you are adding 7 values, the minimum would be -9 x 7 which is -63. That could save a fraction of memory instead of working with a large negative number.

tung_nn83 + 0 comments [deleted]avansharma + 1 comment This was helpful, thanks a ton.

ishujain18123 + 0 comments [deleted]

code60 + 0 comments Great solution if you don't care about scalability or the assumption that the dataset changes over time. Terrible solution if you do.

AvinU + 0 comments [deleted]anthony_cortes94 + 0 comments Since the hour glass can only be a max of 7 digits and the smallest digit is -9, as long as your max value is initialized to less than -63 the results should be correct.

shankar_223 + 0 comments since each value is between -9 to 9 so -9*7 = -63 should suffice

moshe1rib + 0 comments Min value according to the instructions is actually -9 so -10 would be fine :)

chansek + 0 comments maxValue should be initialized with -63. As every value ranges from -9 to 9.

kanishk_vishwa21 + 0 comments Very large negative values are not necessary. See that an hourglass is made up of 7 digits. the sum of 'those' 7 digits can be minimum when each digit is itself minimum, i.e, -9. Hence, the minimum sum will be (7)x(-9), which equals -63. So, we can initialize minimum as -64.

babloo_pe + 0 comments thanks

rublethomas + 0 comments more like initiate to -64. The max value it can get down to is -9*7=-63

vibinmky + 0 comments Otherwise you can set max_value =-Infinity;

chabasinsky + 0 comments -63 is enough. Hourglass takes 7 elements from array. In description is info that one element of array can be min -9. So 7 x -9 = -63.

Kajal1112 + 0 comments Or maybe, max_value = -63, since a[i][j] can have the least value -9 and hence, least value of hourglass can be 7*(-9) i.e. -63.

ghoghollaxman + 0 comments i set maxvalue to -63 and it works.. thanks bro

Masthan + 0 comments max_value = -63; as our input limit is -9 as per the problem constraints.

blharvey + 0 comments you wouldn't need to calculate it seperately just add some logic to control for the first iteration. i=j=0 then max = value

[deleted] + 0 comments Considering that one of the problem constrians is -9 <= arr[i][j] <= 9

You can consider that the lowest Hourglass value will be the one where all the 7 values are -9.

Considering this, you only need to initialize max_value to -63 should be enough.

I didn't realize of that until I resolve the problem, using C++ INT_MIN, and read the editorial.

TheOneCalledSuto + 0 comments Technically initialize it as -9 * 7

lianyuu + 0 comments you can just set the initilize max value as the last hourglass

will_simpson85 + 0 comments min_value will never be less than -63 so set initial max_value = -63

link182_julio + 0 comments i think that the best way is to initialice as null

jonmcclung + 0 comments [deleted]mdumlupinar + 1 comment you can set -63 for the initial value of the max variable, because the possible minimum value of a hourglass can up to be -63. According to the given restrictions, the minimum hourglass can have maximum seven -9. So, this is the initial number for us: 7x-9=-63.

nancy345 + 4 comments how to do this task in C???

mdumlupinar + 0 comments sorry, i am not familiar with c language.

azheruddin617mr1 + 12 comments int main() { int matrix[6][6]; for(int i = 0;i < 6;i++) { for(int j = 0;j < 6;j++) { scanf("%d",&matrix[i][j]); } } int maxsum = -1000,jj = 0; for(int i = 0;i < 4;i++) { int sum = 0; for(int j = jj;j < jj+3;j++) { sum += matrix[i][j]; if(j==jj) sum += matrix[i+1][jj+1]; sum += matrix[i+2][j]; } jj = (jj < 3) ? jj+1 : 0; if(sum > maxsum) maxsum = sum; if(jj != 0) i--; } printf("%d",maxsum); return 0; }

dattagates + 2 comments why have u assigned maxsum=-1000 ? can u elobarate

azheruddin617mr1 + 0 comments the inputs also given in negitive....

flash793 + 0 comments The constraints given say that any element in the array will be at least -9 and be at most 9. The smallest hourglass sum will be -9*7 = -63. So in this case, you just need to initialize max sum to be any value <= -63.

meerakrish + 0 comments why did you use j=jj

Sarath_95 + 2 comments what the below statement does in the code?

if(jj != 0) i--;

franklinvidal + 0 comments jj = (jj < 3) ? jj+1 : 0; // set 0 if jj(collumn pointer) set in one position which allows calculate an hourglass if(sum > maxsum) maxsum = sum; if(jj != 0) i--; // if jj is in a position where a hourglass can be calculated, the line pointer(i) continue in the same line

ragulravi1999 + 0 comments To run loop for same value of i with different values for j untill j maximum limit is reached

bhavgothadiya + 0 comments why not take -1

pa1v_kar + 0 comments [deleted]pa1v_kar + 4 comments **could anyone identify the mistake**int main(){ int arr[6][6]; for(int arr_i = 0; arr_i < 6; arr_i++){ for(int arr_j = 0; arr_j < 6; arr_j++){ scanf("%d",&arr[arr_i][arr_j]); } } int sum[30]; int x=0; int arr_i,arr_j; int largest; for(arr_i=0;arr_i<3;arr_i++) { sum[x]=0; int count=0; for(arr_j=arr_i;count<3;arr_j++) { if(count==0) { sum[x]+=arr[arr_i+1][arr_j+1]; } sum[x]+=arr[arr_i][arr_j]; sum[x]+=arr[arr_i+2][arr_j]; ++count; } ++x; } largest=sum[0]; for(int i=1;i<=x;i++) { if(largest<sum[i]) largest=sum[i]; } printf("%d",largest); return 0; }

Nidheesh_P + 2 comments in for loop try i<4 instead of i<3

manny_capacidade + 1 comment Whats the reason behind i<4..Not able to get the reason.Can you explain please

fhasson91 + 0 comments there are 4 hourglasses vertically and 4 hourglasses horizontally

sakshi_munya + 0 comments Thanks a lottt.....Nidheesh.

uniquechhetrii + 2 comments for(arr_i=0;arr_i<3;arr_i++) { sum[x]=0; int count=0; for(arr_j=arr_i;count<3;arr_j++) { if(count==0) { sum[x]+=arr[arr_i+1][arr_j+1]; } sum[x]+=arr[arr_i][arr_j]; sum[x]+=arr[arr_i+2][arr_j]; ++count; } ++x;

I didnt understand this part. Can somebody help me out in this?

chadams + 0 comments His algorithm is getting the middle element of the hourglass on the first pass through and then incrementing the top and bottom rows of the hourglass. He increments count to track the amount of loops needed to read a hourglass and increments x to correspond to the position in the hourglass; 0,1,2 respectively.

vigneshiyer66661 + 0 comments [deleted]

rachehua + 0 comments If this is C++, how come the code is all in main function and not in the function they told us to write it as?

kmerotha1996 + 0 comments int hourglassSum(vector> arr) { int i,j,sum=0,x=0,p=-50,count=0; for(i=0;i<4;i++){ sum=0; for(j=0;j<4;j++){ sum=arr[i+1][j+1]+arr[i][j+1]+arr[i][j+2]+arr[i][j]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]; if(p } return(p); }

chernandez2 + 5 comments This code passes all the test cases

#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; int main(){ vector< vector<int> > arr(6,vector<int>(6)); for(int arr_i = 0;arr_i < 6;arr_i++){ for(int arr_j = 0;arr_j < 6;arr_j++){ cin >> arr[arr_i][arr_j]; } } vector<int> res; res.reserve(18); for(unsigned int j=0; j<4;++j){ for(unsigned int i=0; i<4;++i){ res.push_back(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]); } } cout<<*max_element(res.begin(),res.end())<<endl; return 0; }

160302032CSE + 2 comments can anyone explain this part

res.reserve(18); for(unsigned int j=0; j<4;++j){ for(unsigned int i=0; i<4;++i){ res.push_back(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]); } } cout<<*max_element(res.begin(),res.end())<

revathymanulal + 0 comments - res.reserve(18) is like declaring an array of size 18 though am not sure why size 18 was choosen ,I think 16 would have done the job.

-the two for loops with contraints <4 is for the purpose of forming the hour glass (had it been <6 it would have resulted in indexing issues)

-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] these are the indexes which form an hour glass, the sum of every hour glass is calculated and push to the res

-cout<<*max_element(res.begin(),res.end()) the maximum value in res is choosen as the output

revathymanulal + 4 comments I used a similar approach but dint keep on storing all of the values of hour glass instead just kept on swaping the values incase the value of new hour glass was greater than the previous one.

import sys a = [] for arr_i in xrange(6): arr_temp = map(int,raw_input().strip().split(' ')) a.append(arr_temp) max_sum =-63 for i in range(4): for j in range(4): check_sum = a[i][j]+a[i][j+1]+a[i][j+2]+a[i+1][j+1]+a[i+2][j]+a[i+2][j+1]+a[i+2][j+2] if check_sum > max_sum: max_sum = check_sum print max_sum

tppiotrowski + 0 comments [deleted]nr_selcuk + 4 comments why the range(4)? I think it should be the range(len(a)-2) in order to satisfy any size...

DarkC_oder + 0 comments [deleted]sukhraj5 + 0 comments The problem specifies the matrix is always 6x6

sandeepini + 0 comments Because our array is of 6x6. when we run arr[i][j+2] In j+2=5(When loop run second last time (3+2=5)) which valid . This is the reason.

sandeepini + 0 comments Because our array is of 6x6. when we run arr[i][j+2] In j+2=5(When loop run second last time (3+2=5)) which valid . This is the reason.

pathansuhana969 + 0 comments why it is not working in python3? any one pls explain.

ankitiitism + 0 comments only 4/9 test cases passed , can any one identify bug.

# include

using namespace std; int main() { int arr[6][6] ; int t=6; while(t--) { for(int i=0; i<6; i++) cin>>arr[6-t][i]; } vectorv; int n=6; for(int i= 0; i<4;i++) for(int j= 0; j<4; j++) { int sum=0; 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]); v.push_back(sum); } int max = *max_element(v.begin(), v.end()); cout<

typicallucas + 1 comment Hi, you're including a bunch of extraneous libraries. You are just using vector, iostream, and algorithm.

The rest could be deleted :) Cheers

banerjeeunmesha + 1 comment I didnot include any extraneous libraries, I did my code in c++,kindly help me...thank you for your time and help my code:

# include

using namespace std; void sum(int[][6]); int main() { int a[6][6]; int i,j; cout<<"enter val\n"; for(i=0;i<6;i++) { for(j=0;j<6;j++) { cin>>a[i][j]; } } sum(a); return 0; } void sum(int a[][6]) { int l=0,m=0; int i,j,max; int sum[4][4]; for(i=0,j=0;i<=3,j<=3;j++) { if(j==3) { sum[l][m]=a[i][j]+a[i][j+1]+a[i][j+2]+a[i+1][j+1]+a[i+2][j]+a[i+2][j+1]+a[i+2][j+2]; i++; j=-1; } else { sum[l][m]=a[i][j]+a[i][j+1]+a[i][j+2]+a[i+1][j+1]+a[i+2][j]+a[i+2][j+1]+a[i+2][j+2]; } m++; if(m==4) { l++; m=0; } } max=sum[0][0]; for(i=0;i<4;i++) { for(j=0;j<4;j++) { if(sum[i][j]>=max) { max=sum[i][j]; } } } cout<<"max"<

typicallucas + 1 comment hi, i think you're more likely to get help if your code is more readable. Wrap your code with three back-ticks and that should help improve the

banerjeeunmesha + 1 comment # include

using namespace std; void sum(int[][6]); int main() { int a[6][6]; int i,j; cout<<"enter val\n"; for(i=0;i<6;i++) { for(j=0;j<6;j++) { cin>>a[i][j]; } } sum(a); return 0; } void sum(int a[][6]) { int l=0,m=0; int i,j,max; int sum[4][4]; for(i=0,j=0;i<=3,j<=3;j++) { if(j==3) { sum[l][m]=a[i][j]+a[i][j+1]+a[i][j+2]+a[i+1][j+1]+a[i+2][j]+a[i+2][j+1]+a[i+2][j+2]; i++; j=-1; } else { sum[l][m]=a[i][j]+a[i][j+1]+a[i][j+2]+a[i+1][j+1]+a[i+2][j]+a[i+2][j+1]+a[i+2][j+2]; } m++; if(m==4) { l++; m=0; } } max=sum[0][0]; for(i=0;i<4;i++) { for(j=0;j<4;j++) { if(sum[i][j]>=max) { max=sum[i][j]; } } } cout<<"max"<

banerjeeunmesha + 1 comment how to add back ticks? i am unable to add the pdf file as well plzz help.

typicallucas + 0 comments [deleted]

ramin_shahab + 0 comments :O Are you using all those includes?

arka_cool1996 + 0 comments Simple and efficient and also easy to understand . Thank you sir.

arka_cool1996 + 0 comments Is there any specific reason why you ran the j loop instead of the i loop first while finding the sum of the hourglass or is it just a matter of choice.

joshknows09 + 0 comments Can you go over this a little bit?What are we trying to solve and how?^

as6378320 + 1 comment I think python solution is simple and consume less memory space

print(max([sum(arr[i-1][j-1:j+2] + [arr[i][j]] + arr[i+1][j-1:j+2]) for j in range(1, 5) for i in range(1, 5)]))

timothyrmeehan + 0 comments Nice one liner!

DAMwingtsun + 0 comments Can someone help me with understanding 'i'ths and 'j'ths and a resource to show one how to manipute those for traversing through an array. Like azheruddin617mr1 here with j = jj and jj+3 and jj+1?

Emily1691 + 0 comments What language is this for?

mailtokks290199 + 0 comments can you explain what have you done here: int maxsum = -1000,jj = 0; for(int i = 0;i < 4;i++) { int sum = 0; for(int j = jj;j < jj+3;j++) { sum += matrix[i][j]; if(j==jj) sum += matrix[i+1][jj+1]; sum += matrix[i+2][j]; } jj = (jj < 3) ? jj+1 : 0; if(sum > maxsum) maxsum = sum; if(jj != 0) i--; }

Jagdeep_one7 + 2 comments # include

int main() { int a[6][6],hg[3][3]; int i,j,x,y,sum=0,max=-63; for(i=0;i<6;i++) { for(j=0;j<6;j++) { scanf("%d",&a[i][j]); } }

`for(i=0;i<4;i++) { for(j=0;j<4;j++) { for(x=i;x<i+3;x++) { for(y=j;y<j+3;y++) { if(x==i+1&&y==j) continue; else if(x==i+1&&y==j+2) continue; else hg[x][y]=a[x][y]; sum+=hg[x][y]; } } if(sum>max) { max=sum; } sum=0; } } printf("%d",max); return 0;`

}

fooboogoobear + 0 comments Holy for-loops, Batman

sukur710 + 0 comments do you think that your code will be accepted even after using infinite no of for loops?

Jagdeep_one7 + 0 comments [deleted]

nithishjprabhu + 0 comments Can u check this?

while (true) { if (mainControl + buffer > n + 1) { break; } while (true) { if (ik + buffer > n) { ik = mainControl++; jk = 0; break; } int sum = 0; for (int i = ik; i < ik + 3; i++) { if (jk + buffer > n) { jk = jk + 1; ik++; break; } for (int j = jk; j < jk + 3; j++) { int iStartIndex = ik; int jStartIndex = jk; int i1 = a[i][j]; if (i == iStartIndex || i == iStartIndex + 2) { sum = sum + i1; } else if (i == iStartIndex + 1) { iStartIndex++; jStartIndex++; if (iStartIndex == i && jStartIndex == j) { sum = sum + a[i][j]; } } } }

balajilitsv + 0 comments or initialize it to any value less than -63, because the input values of the array ranges from -9 to +9. So a hour glass can contain a maximum of 7 times -9, which sums up to -63. Any value greater than -64 can be accepted to swap the max variable, right!

**HotIce!**prashantpx + 0 comments Thanks

anantchaturvedi1 + 0 comments I did it in Python 3 and I initialized it as None, and put an if condition to check if result_max is none or not

deepakkushwaha61 + 0 comments if we dont know the input then there is no chance of getting hourglass

justbecause1337 + 0 comments Utilizing the None, nil, or null the abscense of a value is useful for preventing issues like this.

NishthaKalra + 0 comments You can also intialize max value to -Infinity. In Python, you can do that by -float('inf')

shashwatsahai5 + 0 comments just to be a little more precise, set the max value to -63 initially because according to the constrains, thats the least value possible

abbng12345 + 0 comments wow you easly explain a whole material in one sentence i realy appriciat your performance dog training at home

Paritybit + 0 comments Or Min int value. worked

eseguraa92 + 0 comments Since the boundaries are -9 just initialize it to -9 * 6 and that's it

milanvanwouden + 0 comments initialize max to INT_MIN

DangerBhai + 0 comments no sir, this will not work anywhere (atleast in c++14).

braceman + 2 comments yeah you can init max value to one less than the least value possible, in this case its '-55'

mandar012 + 2 comments least value of sum possible = -9*7 = -63 so init max = -64

braceman + 0 comments thanks for the correction mandar012 and my apologies for posting such wrong ans

lose311 + 2 comments Why not just use

`max = -63`

? If the whole array is`-9`

then max will never change and output correct answer of`-63`

jonmcclung + 1 comment You're right, that's the best initial value.

jonjanelle1 + 0 comments In this case I'd say using Integer.MIN_VALUE would be a better choice. This will make it easier to convert your algorithm to one that can be used on any size array and with different integer bounds

tOOtl + 1 comment It's not that important here, but by initialising to a lower value than any hourglass could have (for example -64), you'll be able to identify more easily whether a bug is causing the max value to never update (max remains at -64) or if max is updating but not to the correct value.

jonmcclung + 0 comments that's a good idea! whenever you can decrease the number of possible causes of a problem, that's a good thing!

aman1324 + 0 comments -64

leonkni10 + 0 comments [deleted]malayladu + 1 comment Hello,

I hvae written a code in PHP and test case 5 got failed.

I am thinking that code should past all test cases. Didn't know why it failed test case 5.

PS: I didn't initialize max value to 0

keencorsiga21 + 1 comment May I see your code?

AvinU + 0 comments [deleted]

kamalnamdeo + 0 comments You can actually set -9, which is given in problem statement. :)

manan5439 + 0 comments i have 1 idea for that. first find min value from max=0arr[j][i]

suryabteja + 0 comments Why is that? I dont understand the logic in it.

lobheshdhakarma1 + 1 comment i intiliza max value -999 iam getting error can u have a c code

prakash_arya + 0 comments [deleted]

dban10 + 0 comments Good catch!!

bence_meszaros + 0 comments I used

int max = numeric_limits<int>::min();

baby_groot + 0 comments In python 3 I have used, MIN = -sys.maxsize -1

chandukotari + 2 comments yes, you should not intialize maximum to zero its better to intialize with a large negative number

banerjeeunmesha + 0 comments why am i getting timeout? my complexity is O(n^2)(for finding max)and for computing hourglass sum itts O(n)

1l0v3c0d3 + 0 comments Not just better, mandatory; initializing to zero is wrong.

kjadeja7 + 0 comments thank you

abhiram_n + 1 comment initialise to a negative number

NickWoodward + 0 comments or just test for and initialise the total to the first hourglass value

kavyasree42 + 0 comments i initialised max value with -63. it worked

abhinavkinshuk + 0 comments Just intialize max value to -63.

vash47 + 0 comments For Python 3, the minimum value an integer can have is:

min = -sys.maxsize -1

adit2storm + 0 comments then what should be taken

ksved + 0 comments They have stated that minimum value of the element is -9. Therefore minimum value of an hourglass is -9*7 = -63. Initialize max value to -63.

Eddy_cool + 0 comments //Here MAX is already 0 after that it cant pass the two testcase;

int MAX=0; int total=0; int main(){ double arr[10][10]; for(int i=0;i<6;i++){ for(int j=0;j<6;j++){ cin>>arr[i][j]; } } for(int i=0;i<4;i++){ for(int j=0;j<4;j++){ total=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]; MAX=max(total,MAX); } } cout<

akshay_borse29 + 0 comments Initialize max_value = -63, as the minimun value of an hourglass can be only -63. No need to assign large negative value as -99999.

gpaulo42 + 0 comments Tks buddy. I was expend a long time to try fix it. My solution to get the minor int allowed:

int maxHourGlass = -1 * (int) Math.pow(2,32);

codextj + 0 comments [deleted]mkhan41 + 0 comments You can actually set it to -63 as we sum up 7 values at a time, and the least these values can be is -9 as per the specs.

min = -63 = -9 * 7

dgaban + 0 comments lol I made this mistake the first time too.

[deleted] + 0 comments The maximum value can be a negetaive number. So initialize the max values to -63 (-9 * 7) because there are 7 elements in the hour glass and all can take the value of -9 in some case whose sumn will be the least number.

conghaikct + 0 comments cause the hourglass given by sum of 7 integer value from -9 to 9 . You should set max_value = -64 or lower . Sorry about my English is not good.

laurent_mundell + 0 comments [deleted]17pa1a05g0 + 0 comments Instead we can initialize max value to -64 as the max negative we can obtain is 7*-9

diego_mariani + 0 comments [deleted]elsporko + 1 comment I set the value to None (Python 3) and set the max_value the first time it is calculated. Others have suggested that setting the value to -63 (7 * -9) is sufficient, which it is, but what happens when the spec changes (real world) and now we need to reset the initial max_value to whatever the lowest possible value could be.

integer.MIN_VALUE works as well. Generally I am against 'magic numbers' so None or the absolute lowest known value make the solution more scalable IMHO.

tpnewhistory + 0 comments Cool, thanks for the feedback!

rakeshreddy5566 + 2 comments pattern is everything (for pythoholics)

def hourglassSum(arr):

`li=[]`

`for i in range(len(arr)-2): for j in range(len(arr)-2): li.append(sum(arr[i][j:j+3]+arr[i+2][j:j+3])+arr[i+1][j+1]) return max(li)`

justbecause1337 + 0 comments Coming from C++ I guess the question is does the underlying implementation when sent to a exe maker such as py2exe or when interpretted take into account things like memory allocation etc. While in this case storing all values is trivial what about in cases where hte list could potentially be thousands of items long. Even with the use of iterables we're talking about a memory. I assume you could say the comparison can either be done in loop or @ the end as this code does.

shadow_of_code + 0 comments rakeshreddy5566 nice code dude

adammoses + 0 comments Yea, make sure to set max to whatever the first value is.

erdemkeren + 1 comment in C# you can initialize it like

`var maxValue = int.MinValue`

too.adammoses + 0 comments Yea, it's cool checking solutions between languages. Lots of options.

wkshum99 + 0 comments thanks, you're awesome!

tejas_kharva + 0 comments Or just use Integer.Min_Value

blackjar72 + 0 comments Since it's like initialized before starting to calculate hourglasses the best / simplest idea is to initialize it to the minimum integer value. In Java Integer.MIN_VALUE; in C++ climits::INT_MIN.

If your language doesn't have anything like this its an easy guess that the minimum value of a 32 bit signed integer can be used, since most languages use this as a default integer type.

pankajnu + 0 comments Yes - remember your max value can very well turn out to be a negative number.

bardia_alavi + 0 comments min value is -9 and we have 7 elements to sum. Therefore the sum cannot be less than -63. If you initialize to anything less than -63 you are good.

harsh_33 + 0 comments i have passed it even g=-1000

guoliangxu1987 + 0 comments use

`float('-inf')`

in Pythonfpeven + 0 comments You can initialize max value less than -63.

**int max = -9*7;**Because there is a constraint:**-9 <= arr[i][j] <= 9**So there is no point to use value less than -9*7christian_eik + 0 comments A nice solution to this for Python is to initialize it to

`-math.inf`

.3nomis + 0 comments I've done if (not max) or (max < n): max = n

vikrantpailkar + 0 comments You may initialize max value to -63(given that the range of values is from -9 to 9).

aizazchaudary + 0 comments [deleted]mohammad_kaab + 0 comments I've just set it to null, and used if condition to check if it's null or not, then I'm going to fill it with the first value.

ayushtalesara27 + 0 comments You could also append all the values to an array, and find the largest value.

gusaingaurav1231 + 0 comments I am a slut. Fuck me please... you are very handsome call me immediately... aah...ooh

shivayl + 0 comments You can also initialize it to -63 or -9 * 7, which is the minimum possible sum

shubhamp2494 + 0 comments mathematically smallest number is "-infinity". So we should initiate the variable like:

import math x = -(math.inf)

aadithyavarma + 0 comments It was said in the question that value of integers are between -9 to 9. You can initialize the max value to anything less than -63 (7 times -9, since there will be 7 numbers and least sum of them can be -63).

Link2naqvi + 0 comments i would day , initialize to -1000

m_weizman + 0 comments [deleted]yubarajpoudel708 + 0 comments Working answer

`static int hourglassSum(int[][] arr) { int rowCount = arr.length; int colIndex = 0; int rowIndex = 0; int total = 0; while(rowIndex < rowCount-2) { while(colIndex < arr[rowIndex].length-2) { int sum = 0; for(int i = rowIndex; i < rowIndex+3; i++) { if(i == rowIndex+1) { sum += arr[i][colIndex+1]; } else { for (int j = colIndex; j < colIndex+3; j++) { sum += arr[i][j]; } } } if(rowIndex == 0 && colIndex == 0) { total = sum; } else if (sum > total) { total = sum; } colIndex ++; }`

colIndex = 0; rowIndex ++; } return total; }sankalpnitj + 0 comments Yeah, that was a subtle change in the code we should always remember while finding maximum value stuff. Thanks.

ahamedkabeer279 + 0 comments Thanks man..

zohre_1987 + 0 comments For JS initialize sum with Number.NEGATIVE_INFINITY.

sarankumar_b2018 + 0 comments Yeah great man, I was also stuck with that test case. So i have initialize as larger negative value.

RishC + 21 comments Python3 answer

sum = [] for i in range(len(arr)-2): for j in range(len(arr)-2): sum.append(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]) print(max(sum))

ndakyildiz + 0 comments Brilliant!

madhukar_charla + 1 comment //Similar to this Java :) List sum = new ArrayList(); for(int i=0; i<4; i++){ for(int j=0; j<4; j++){ sum.add(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]); } } System.out.println(Collections.max(sum)); }

rishabhshairy29 + 2 comments why we are iterating upto 4 ??

mayank113463 + 0 comments coz after 4 iteration will ends the matrix .if you count 6*6 matrix and if you need only 3*3 than it will be possible only uptu 4 iterartion

9 -9 -9 1 1 1 0 -9 0 4 3 2 -9 -9 -9 1 2 3 0 0 8 6 6 0 -->>4th line 0 0 0 -2 0 0 0 0 1 2 4 0

you can iterate til 4th line because next iteration give 2 lines only

andrew_wijaya + 0 comments Just check the constraints in the problem statement. The algorithm is meant to solve it for a 2D array of size 4x4. Easy to generalize, just get the array dimensions and use it for iteration thresholds.

nanda_ananya + 1 comment Could you please explain!

gt_silva_e + 0 comments They are storing all the sums for every hourglass in the array/list. What I don't like about this solution is that you need more memory (allocate another array/list) and finally you need the max function, which may add extra complexity depending on the implementation. I prefer the max variable + if solution better.

serious_nick + 4 comments One liner in Python 3:

print(max([sum(arr[i-1][j-1:j+2] + [arr[i][j]] + arr[i+1][j-1:j+2]) for j in range(1, 5) for i in range(1, 5)]))

mathurk29 + 0 comments As array indices also start from zero, it would be convenient to let range function start from 0 (which it does by default):

print(max([sum(arr[i][j:j+3] + [arr[i+1][j+1]] + arr[i+2][j:j+3]) for i in range(4) for j in range(4)]))

askz6 + 1 comment Why does the max function contain brackets that also wrap around everything inside?

serious_nick + 0 comments it's a list comprehension https://python-course.eu/list_comprehension.php

meysam81 + 0 comments Excellent Well done

donggangcj + 0 comments print(max(sum(arr[i-1][j-1:j+2] + [arr[i][j]] + arr[i+1][j-1:j+2]) for j in range(1, 5) for i in range(1, 5))) no '[]' list generator,more faster!

alphasingh + 0 comments My Attempt :)

A = [] S = [] [A.append(list(map(int, input().split()))) for i in range(6)] [S.append(sum(A[i][j:j+3]+A[i+2][j:j+3])+A[i+1][j+1]) for i in range(4) for j in range(4)] print(max(S))

vivek0079 + 0 comments awesome and cool:)

CruiseDevice + 0 comments Python help me understand such questions easily

divyammehta + 0 comments Even I thought of the same solution but it doesnt pass a lot of test cases

rishravi + 0 comments To save space, you can check for max sum with every calculation of the hourglass sum. So instead of having an array with all values and then comparing the max, we can get the result as we traverse :)

alex_k_stamatis + 0 comments Nice simple solution! I feel stupid that I solved it with a 4D array now...

geekidharsh + 0 comments prefect pythonian solution

nitinkanagaraj + 0 comments Why is range(len(arr)-2) ?

dan_dinu + 2 comments A similar NodeJS solution:

var sum = []; for (i = 0; i < arr.length - 2; i++) { for (j =0; j < arr.length - 2; j++) { sum.push(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]); } } console.log(Math.max(...sum));

DavisOkoth + 1 comment Oh, cool. I did something similar but forgot Math.max(). I had to do a sort then get the final element in the array. Thanks!

lowadb + 0 comments [deleted]

techieviking + 0 comments [deleted]

vermashivani801 + 0 comments amazing !

vasil_kolomiets + 0 comments my approch has -1 calculation on each glass and no additional array sum. Look on it. . '''

def hourglassSum(arr):

len_arr = len(arr)

n=(len_arr-2)**2

s_max = None

for k in range(n):

i = k//(len_arr-2)

j = k%(len_arr-2)

if j==0: # new row glass sum

_ = sum((arr[i][0],arr[i][1],arr[i][2],

arr[i+1][1],

arr[i+2][0],arr[i+2][1],arr[i+2][2])

if(s_max is None):

s_max = _

else: # next glass in the same row sum calc

_ += (-arr[i][j-1]-arr[i+1][j]-arr[i+2][j-1] + \

arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j+2])

s_max = max(s_max,_)

return s_max

'''timothyrmeehan + 0 comments Here's a python3 one-liner.

max([sum(arr[j][i:i+3]) + arr[j+1][i+1] + sum(arr[j+2][i:i+3]) for j in range(len(arr)-2) for i in range(len(arr[0])-1)])

This code uses list comprehension to build a list of hour glass sums. For the rows where 3 values are added, I used

`sum(arr[row][col:col+3])`

then summed all values. The code starts at i, j = 0, 0 and I used the size of the array to limit the i and j terms. Think nested loopqueen_of_stardom + 0 comments def hourglassSum(arr): addn=[] for i in range(6): for j in range(6): top=arr[i][j]+arr[i][(j+1)%6]+arr[i][(j+2)%6] middle=arr[(i+1)%6][(j+1)%6] bottom=arr[(i+2)%6][j]+arr[(i+2)%6][(j+1)%6]+arr[(i+2)%6][(j+2)%6] add=top+bottom+middle addn.append(add)

`return max(addn)`

This is my attempt. but it doesnt pass all testcases for some reason. can anyone explain?

16NM1A0544 + 0 comments [deleted]kuertzva + 0 comments you can avoid writing the long sequence of additions the following way:

1) create a variable called total equal to arr[i+1][j+1]

2) create a third loop of k in range(3). 3) On each iteration of k, add arr[i][j+k] and arr[i+2][j+k] to total. 4) append total to kJotune + 0 comments Althought it's an elegant writing, it's really poor in terms of performance for the real world. That been said, it's probably the funiest solution for this simple exercice :D

abhi7585 + 0 comments [deleted]

milad + 6 comments How the heck is this problem ranked as easy? Am I missing something or do people jus tlook at the solutions after 1 glance at the problem?

vaddi_party + 0 comments they are easy compared to the hard level problems. :)

snaran + 0 comments I agree with milad. This one was harder than https://www.hackerrank.com/challenges/sparse-arrays?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=3-day-campaign.

To make matter more complicated, I solved it by calculating the new hourglass value by subtracting out the old cells and adding the new cells, and made the hourglass size (3x3) configurable, and the array size configurable too. But even without this, it is harder than the one mentioned above.

techniker + 0 comments True the question isn't easy.

MoBotan + 0 comments I am guessing because you just have to brute force the solution. There is no smart/advanced way to get the answer.

martin89 + 0 comments It is easy! If not to you then this good practice for you so that later you will see that it is easy.

allanjpoindexter + 0 comments It really is easy if you take time to figure out what makes a valid hourglass first:

Once you realize that an hourglass would never exceed the length of the rows or the columns, you can build your for loops accordingly.

tony_cottam + 10 comments I think where most people are having problems (and where I

*was*having problems) is that the array is being read in and then processed on opposite coordinates ( e.g. read in as (x, y) but then process as (y, x) ).I decided this was the problem for me after I read in the array as a 1D array and then was able to solve no problem.

darnesmeister + 0 comments thanks man, didn't realize this without your hint

jlipata + 1 comment This is true. I tried outputting the matrix to the screen in standard x,y format, it does not look like the input. This caused a lot of confusion and time wasted while debugging. IMO, Hackerrank should fix this.

carolinebholmes + 0 comments I consider it a good lesson in paying attention to existing code (I fell prey to this problem as well)

andrewseaman35 + 0 comments It doesn't help that the initial test case passes when the indexing is switched.

debashishmitra + 1 comment That was the thing. Misleading pre provided scanning code. It scans by columns - not by rows - which I assume most would not expect. I was so sure mine was right but had no idea why certain test cases were failing. Only thing I had to change was to switch the for statements (outer to inner and inner to outer) and all test cases passed.

Yours is the most observant and helpful comment. Thanks much

abbng12345 + 0 comments thanks dear you solve my problem i am face this problem from last two days, one again a lot of thanks how to communicate with cats

arvind002 + 0 comments thanks bro, you saved my day!!

den_no_lemurrr + 0 comments 2d matrix usually has array[row][column] format, not x,y

paul20110808 + 0 comments Yes, this problem set a little trap.

hugss + 0 comments [deleted]hugss + 0 comments THANK YOU!!!

sahajarora + 0 comments Thank you!

jhall1468 + 7 comments A Javascript solution using

`O(n*m)`

time complexity and`O(1)`

space complexity.function hourGlass(arr) { // we could set this to 3 given the problems constraings, but this allows changes maxX = 3; // + (arr[0].length % 3) maxY = 3; // + (arr.length % 3) total = -Infinity; // has to be -64, but // begin at y == 0 for (let y = 0; y <= maxY; y++) { for (let x = 0; x <= maxX; x++) { // sum the top of hourglass let sum = arr[y][x] + arr[y][x+1] + arr[y][x+2]; // get the middle of hourglass sum += arr[y+1][x+1]; // sum the bottom of hourglass sum += arr[y+2][x] + arr[y+2][x+1] + arr[y+2][x+2] // don't store result to keep space complexity down if (total < sum) total = sum; } } return total; }

chadwalt + 3 comments Hey awesome solution, just a quick question why use -Infinity

MoBotan + 0 comments You can't set the initial value of 'total' to 0, because the answer might be lower. To avoid that, set the initial value to the lowest possible (-infinity).

The smallest number allowable for any of the numbers in the hourglass is -9. If all the numbers in an hourglass are -9, the lowest possible value for an hourglass is -63. So an initial value of -63 is ok too.

gacevic_danilo + 0 comments you can also use -64 since the lowest possible value is -63 :)

k_klapczynski + 0 comments I think more general and better solution is to declare maxSum outside of loop and then after calculating sum add:

<

Sort 1872 Discussions, By:

Please Login in order to post a comment