Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 39 additions & 50 deletions hourglass_challenge_java
Original file line number Diff line number Diff line change
@@ -1,50 +1,39 @@
// C++ program to find maximum sum of hour
// glass in matrix
#include<bits/stdc++.h>
using namespace std;
const int R = 5;
const int C = 5;

// Returns maximum sum of hour glass in ar[][]
int findMaxSum(int mat[R][C])
{
if (R<3 || C<3)
return -1;

// Here loop runs (R-2)*(C-2) times considering
// different top left cells of hour glasses.
int max_sum = INT_MIN;
for (int i=0; i<R-2; i++)
{
for (int j=0; j<C-2; j++)
{
// Considering mat[i][j] as top left cell of
// hour glass.
int sum = (mat[i][j]+mat[i][j+1]+mat[i][j+2])+
(mat[i+1][j+1])+
(mat[i+2][j]+mat[i+2][j+1]+mat[i+2][j+2]);

// If previous sum is less then current sum then
// update new sum in max_sum
max_sum = max(max_sum, sum);
}
}
return max_sum;
}

// Driver code
int main()
{
int mat[][C] = {{1, 2, 3, 0, 0},
{0, 0, 0, 0, 0},
{2, 1, 4, 0, 0},
{0, 0, 0, 0, 0},
{1, 1, 0, 1, 0}};
int res = findMaxSum(mat);
if (res == -1)
cout << "Not possible" << endl;
else
cout << "Maximum sum of hour glass = "
<< res << endl;
return 0;
}
import java.util.*;

public class Solution {

// Returns maximum sum of hour glass in ar[][]

public static int hourglass(int[][] arr,int R,int C){
int ans = Integer.MIN_VALUE;
for(int i=0;i<R-2;i++){
for(int j=0;j<C-2;j++){

// Considering arr[i][j] as top left cell of
// hour glass.


int 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];

ans=Math.max(ans,sum); //If previous sum is less then current sum i.e. ans then update new sum in ans
}
}
return ans;
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
int[][] arr = {{1, 1, 1, 0, 0},
{0, 1 ,0, 0 ,0},
{1 ,1 ,1 ,0 ,0},
{0 ,0 ,0, 0, 0},
{0 ,0, 0 ,0, 0 }};

int R=arr.length; // No of rows in Matrix

int C=arr[0].length; // No of Columns in matrix

System.out.print(hourglass(arr,R,C));
}
}