I PATTERN SUM IN 2D ARRAY

 Context

Given a  2D Array:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

 representation:

a b c
  d
e f g


Output Format

Print the maximum hourglass sum in .

 Input

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

 Output

19

Explanation

 contains the following hourglasses:

1 1 1   1 1 0   1 0 0   0 0 0
  1       0       0       0
1 1 1   1 1 0   1 0 0   0 0 0

0 1 0   1 0 0   0 0 0   0 0 0
  1       1       0       0
0 0 2   0 2 4   2 4 4   4 4 0

1 1 1   1 1 0   1 0 0   0 0 0
  0       2       4       4
0 0 0   0 0 2   0 2 0   2 0 0

0 0 2   0 2 4   2 4 4   4 4 0
  0       0       2       0
0 0 1   0 1 2   1 2 4   2 4 0

The hourglass with the maximum sum () is:

2 4 4
  2
1 2 4
SOLUTION:
package TwoDArrays;
import java.util.*;
public class IpatternSum {
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int iR=sc.nextInt();
        int iC=sc.nextInt();
        
        int arr[][]=new int[iR][iC];
        for(int i=0;i<iR;i++)
        {
            for(int j=0;j<iC;j++)
            {
                arr[i][j]=sc.nextInt();
            }
        }
        int sum=0;
        int max=-30;
        for(int i=0;i<4;i++)
        {
            sum=0;
            for(int j=0;j<4;j++)
            {
                sum=arr[i][j]+arr[i][j+1]+arr[i][j+2];
                sum+=arr[i+1][j+1];
                sum+=arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];
            if(sum>max)
            {
                max=sum;
            }
            }
         
        }
         System.out.println(max);
    }
    
}

Comments

Popular posts from this blog

PROGRAM TO FIND FACTORIAL OF A NUMBER USING RECURSION

PROGRAM TO FIND THE COUNT OF PARTICULAR NUMBER IN AN ARRAY

TELEPHONE BOOK USING HASHMAP