Friday, March 13, 2020

2D Array Problem Solution

Problem:

https://www.hackerrank.com/challenges/30-2d-arrays/problem

Solution:


import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class TwoDArray {
        private static final Scanner scanner = new Scanner(System.in);

        public static void main(String[] args) {
            int[][] arr = new int[6][6];

            for (int i = 0; i < 6; i++) {
                String[] arrRowItems = scanner.nextLine().split(" ");
                scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

                for (int j = 0; j < 6; j++) {
                    int arrItem = Integer.parseInt(arrRowItems[j]);
                    arr[i][j] = arrItem;
                }
            }

            scanner.close();
            System.out.print(largestHourGlassSum(arr));
        }
        public static int largestHourGlassSum(int [][] a){
            List sums = new ArrayList();
            for(int r =0;r<4;r++){
                for(int c =0;c<4;c++){

                    Integer glassSum = a[r][c]+a[r][c+1]+a[r][c+2]
                            +a[r+1][c+1]
                            +a[r+2][c]+a[r+2][c+1]+a[r+2][c+2];
                    sums.add(glassSum);
                }   
            }
            Collections.sort(sums);
            return sums.get(sums.size()-1);
        }
    }


Run : 


Sample 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
Sample Output

19

No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...