Java2 D Array Problem

The problem context involves a 2D array of integers, where the task is to find the maximum sum of an 'hourglass' in the array. An hourglass in this context is defined as a subset of values with indices falling into this pattern in the array's graphical representation: a b c, d, e f g.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Java2 D Array Problem HackerRank solution using CodeRankGPT:

The solution approach involves iterating over the 2D array and calculating the sum of every possible hourglass. It uses two nested loops to traverse the array, and for each element, it checks if an hourglass can be formed. If yes, it calculates the sum of the hourglass and compares it with the current maximum sum. If the calculated sum is greater than the current maximum, it updates the maximum. Finally, it prints the maximum sum of all hourglasses.


/**
 * 
 */
package com.javaaid.hackerrank.solutions.languages.java.datastructures;

import java.util.Scanner;

/**
 *
 */
public class Java2DArray {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int arr[][] = new int[6][6];
		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 6; j++) {
				arr[i][j] = in.nextInt();
			}
		}
		int maxSum = Integer.MIN_VALUE, sum = 0;
		;
		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 6; j++) {
				if ((i + 2 < 6) && (j + 2) < 6) {
					sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j]
							+ arr[i + 2][j + 1] + arr[i + 2][j + 2];
					if (sum > maxSum)
						maxSum = sum;
				}
			}
		}
		System.out.println(maxSum);
		in.close();
	}
}

If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform