You are not logged in. Please login at www.codechef.com to post your questions!

×

# Hackerrank 2D Array-DS Help

 0 I was solving this problem: 2D Array My approach includes brute-force approach of selecting each element and checking it's neighbouring elements if they are same or not. But somehow my code is giving wrong answer. Here's my code: #include using namespace std; int main() { int a[6][6]; for(int i=0;i<6;i++) for(int j=0;j<6;j++) cin>>a[i][j]; int sum,ans=0; for(int i=1;i<5;i++) { for(int j=1;j<5;j++) { if(a[i][j] != a[i-1][j] || a[i][j] != a[i][j-1] || a[i][j] != a[i-1][j+1] || a[i][j] != a[i+1][j-1] || a[i][j] != a[i+1][j] || a[i][j] != a[i+1][j+1]) sum = a[i][j]+a[i-1][j]+a[i][j-1]+a[i-1][j+1]+a[i+1][j-1]+a[i+1][j]+a[i+1][j+1]; ans = max(sum, ans); } } cout<

 1 Your loop and your hourglass indices are incorrect. Also no need of inequality check as we only need to find maximum sum hourglass. Its a one liner problem. My solution for reference. int main(){ short a[6][6];  register int i,j; int maxsum=-63,sum=0;  for(i=0;i<6;i++) { for(j=0;j<6;j++) { cin>>a[i][j]; } } for(i=0;i<4;i++) { for(j=0;j<4;j++) { 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]; maxsum=max(maxsum,sum); } } cout <
 1 I have edited your code and now it's passing 7 cases out of 7, take a look.. If you initialize ans = 0 your code fails on 3rd and 7th test case. If you take ans = -6 your code passes all test cases but fails on test case no. 7.For ans =-18 you can pass all the test cases. #include using namespace std; int main() { int a[6][6]; for(int i=0;i<6;i++) for(int j=0;j<6;j++) cin>>a[i][j]; int sum,ans=-18; for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { 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]; ans = max(sum, ans); } } cout<
 3 plz upvote need to ask questions.. answered 23 Feb '17, 21:25 0★montycs 105●7 accept rate: 0%
 toggle preview community wiki:
Preview

### Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×310

question asked: 23 Feb '17, 20:18

question was seen: 1,102 times

last updated: 23 Feb '17, 21:25