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

# 2D Array - DS

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

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

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

for e.g , max_value = -99999;

- ID
ivdekov + 2 comments This is helpful, thank you. I used Integer.MIN_VALUE;

ldaicich + 3 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 + 0 comments I think the input variables are defined as primitive type int.

- AU
abhilashupare + 0 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;

}

- NH
successhawk + 0 comments Using your logic, you could use the type byte.

- M
mudit2jain + 1 comment It passed the testcases but why it doesn't runs when initialized to zero?

- PP
prajapple + 0 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 .

- LF
mondayrain + 3 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]- AA
aman1324 + 0 comments Yes. In case the constraints are not there, use Integer.MIN_VALUE.

- AP
anuragpugalia11 + 0 comments yes it worked. thanks

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

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

- TE
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.

- NK
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]

- AB
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.

- NS
sugsurnitsin + 0 comments what is the hour glass

- E
ernestns + 0 comments [deleted] xudonglee + 0 comments Because of the -9<= A[i][j] <=9, so the extrame situation is that all the 7 elem are -9, the sum is -63, and any value that smaller than -63 could be set to the initial value.

- SG
shrewga + 1 comment The least no. possible is -9 * 7 = -63. We can also initialize it to that. :)

- MK
meerakrish + 1 comment Thanks

- SG
shrewga + 0 comments [deleted]

- VA
varun_1995 + 0 comments int max = Integer.MIN_VALUE;

- AN
abhiram_nataraj1 + 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

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

- G
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

- V
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

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

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

- NN
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

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.

- NK
nancy345 + 2 comments how to do this task in C???

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

azheruddin617mr1 + 7 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.

- MK
meerakrish + 0 comments why did you use j=jj

- SK
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

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

- BG
bhavgothadiya + 0 comments why not take -1

- PV
pa1v_kar + 0 comments [deleted] - PV
pa1v_kar + 2 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; }

- NP
Nidheesh_P + 0 comments in for loop try i<4 instead of i<3

- UC
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?

- CA
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.

- VI
vigneshiyer66661 + 0 comments [deleted]

chernandez2 + 1 comment 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; }

- MF
farukhmahammad11 + 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 + 0 comments I used a similar approach but dint I 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

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

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

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

- KS
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

- T
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!

- AA
aman1324 + 0 comments -64

leonkni10 + 0 comments [deleted]malayladu + 0 comments 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

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

jmxdbx + 0 comments Yeah I wonder what percentage of people (me included) wrote everything correct the first attempt, but initialized at 0 ;)

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

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

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

- PK
prakash_arya + 0 comments [deleted]

- DB
dban10 + 0 comments Good catch!!

- BM
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 + 0 comments yes, you should not intialize maximum to zero its better to intialize with a large negative number

- KJ
kjadeja7 + 0 comments thank you

- AN
abhiram_nataraj1 + 1 comment initialise to a negative number

- NW
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

- AA
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<

- TC
tony_cottam + 5 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.

- DS
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)

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

- DM
debashishmitra + 0 comments 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

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

- RC
RishC + 13 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))

- DA
ndakyildiz + 0 comments Brilliant!

- MC
madhukar_charla + 0 comments //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)); }

- AN
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 + 3 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)]))

- KM
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)]))

- AS
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

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))

- V0
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 + 0 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));

milad + 4 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. :)

- SN
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.

- MB
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.

jhall1468 + 1 comment 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 + 1 comment Hey awesome solution, just a quick question why use -Infinity

- MB
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.

- KE
keari + 3 comments Hi, maybe I am confused by what constitutes an hourglass...but wouldn't 15 be the largest hourglass sum for this test case? However the expected output is 13.

1 1 1 0 0 0

**0 1 0**0 0 01

**1**1 0 0 0**0 9 2**-4 -4 00 0 0 -2 0 0

0 0 -1 -2 -4 0

- MK
kravvcu + 2 comments the hourglass you bolded out is 1 + 1 + 9 + 2 = 13 you do not add the two outer 1's in the middle line with the three 1's above the line with 9

- KE
- HA
hoanganh17b + 0 comments [deleted]

- RS
ravi49167 + 0 comments yeah same here.

- HA
hoanganh17b + 0 comments [deleted]

- MK
manoranjan03 + 0 comments My Solution

public class Solution { public static void main(String[] args) {

`Scanner sc = new Scanner(System.in); int[][] a = new int[6][6]; for(int i =0; i<6; i++){ for(int j=0; j<6; j++){ a[i][j] = sc.nextInt(); } } int sum =Integer.MIN_VALUE; for(int i =0; i<4; i++){ for(int j=0; j<4; j++){ int temp = 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(temp>sum){ sum = temp; } } } System.out.println(sum); /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ }`

}

div1998 + 0 comments Incase u've run the code successfully with #3rd and #7th case failed. try out initializing the variable which stores the sum as a negative(eg.-999).Since for values where the sum is negative,it doesnot update the content of max value as a negative value when the variable sum is initialized to zero.

tomade + 2 comments Rather simple and concise in Python 3:

#!/bin/python3 def hoursum(arr, r, c): return sum(arr[r - 1][c-1:c+2]) + arr[r][c] + sum(arr[r + 1][c-1:c+2]) arr = [[int(x) for x in input().split()] for _ in range(6)] ans = max(hoursum(arr, r, c) for r in range(1,5) for c in range(1,5)) print(ans)

- WD
will_deyl + 0 comments Did the same thing essentially. Just shortened it.

arr = [[int(x) for x in input().split()] for _ in range(6)] hoursum = lambda arr,r,c: sum(arr[r-1][c-1:c+2]) + arr[r][c] + sum(arr[r+1][c-1:c+2]) ans = max(hoursum(arr,r,c) for r in range(1,5) for c in range(1,5)) print(ans)

- RM
rmilejcz + 0 comments Wow this is amazing, I had like 50 lines of code. Thank you for this example, it is really helpful. I couldn't figure out how to make the range function work for me here but this makes SO much sense

- MO
kutra21 + 1 comment is test case 3 is incorrect? As the max sum of 13th hour glass is 25 which is obviously max sum in entire matrix. The expected out is shown as -6 .. am I missing here some thing ?

0 6 -7 1 6 3 -8 2 8 3 -2 7 -3 3 -6 -3 0 -6 5 0 5 -1 -5 2 6 2 8 1 3 0 8 5 0 4 -7 4

- AS
logIN + 0 comments how could the max sum of 13th hour glass be 25. Could yoy point out the exact row and column from which you are counting.

Sort 674 Discussions, By:

Please Login in order to post a comment