We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
this is the code from in java but totally with normal array not ArrayList.
import java.util.Scanner;
public class HourGlass {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[][] array = new int[6][6];
// Read input
for (int x = 0; x <= 5; x++) {
for (int y = 0; y <= 5; y++) {
array[x][y] = s.nextInt();
}
}
// Calculate and print the maximum hourglass sum
int max_sum = hourglassSum(array);
System.out.println(max_sum);
}
public static int hourglassSum(int[][] arr) {
int max_sum = Integer.MIN_VALUE; // Start with the smallest possible integer
// Loop through all potential top-left corners of hourglasses
for (int x = 0; x <= 3; x++) {
for (int y = 0; y <= 3; y++) {
// Calculate the hourglass sum for the current position
int sum = arr[x][y] + arr[x][y + 1] + arr[x][y + 2] // Top row
+ arr[x + 1][y + 1] // Middle element
+ arr[x + 2][y] + arr[x + 2][y + 1] + arr[x + 2][y + 2]; // Bottom row
// Update max_sum if the current hourglass sum is greater
if (sum > max_sum) {
max_sum = sum;
}
}
}
return max_sum;
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Dynamic Array
You are viewing a single comment's thread. Return to all comments →
this is the code from in java but totally with normal array not ArrayList.
import java.util.Scanner;
public class HourGlass { public static void main(String[] args) { Scanner s = new Scanner(System.in); int[][] array = new int[6][6];
}