-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHourglass2DArray.java
More file actions
97 lines (73 loc) · 2.68 KB
/
Copy pathHourglass2DArray.java
File metadata and controls
97 lines (73 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.HackerRank;
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 Hourglass2DArray {
/*
* Hacker Rank Algorithm Question - 2D Array - DS Solution
*
* Solved Date : 2019-08-10
* Author : TK Lee
*
* Source : https://www.hackerrank.com/challenges/2d-array/problem
*/
// Complete the hourglassSum function below.
static int hourglassSum(int[][] arr) {
int r = 0;
int maxLength = arr.length-1;
int maxSum = Integer.MIN_VALUE;
int temp = 0;
while ((r+2) <= maxLength){
int c = 0;
while ((c+2) <= maxLength){
temp = arr[r][c] + arr[r][(c+1)] + arr[r][(c+2)] + arr[(r+1)][(c+1)] + arr[(r+2)][c] + arr[(r+2)][(c+1)] + arr[(r+2)][(c+2)];
System.out.println (temp);
if(temp > maxSum) {
maxSum = temp;
System.out.println (maxSum);
}
c++;
}
r++;
}
return maxSum;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
//Manual Test Code;
int[][] testArr = { {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, 2, 2, 4, 0}
};
int[][] testArr2 = {
{-1, -1, 0, -9, -2, -2},
{-2, -1, -6, -8, -2, -5},
{-1, -1, -1, -2, -3, -4},
{-1, -9, -2, -4, -4, -5},
{-7, -3, -3, -2, -9, -9},
{-1, -3, -1, -2, -4, -5}
};
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
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;
}
}
int result = hourglassSum(arr);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}