下面是沙漏问题定义的链接:
https://www.hackerrank.com/challenges/30-2d-arrays
我写了以下程序:
package day11;
import java.util.Scanner;
public class Solution {
public static void main(String ... args){
Scanner scan = new Scanner(System.in);
int[][] arr = new int[6][6];
int maxHourGlassValue = 0;
int temp = 0;
int currMax = 0;
int k = 0, l = 0;
for(int i = 0 ; i < 6 ; i++){
for(int j = 0 ; j < 6 ; j++){
arr[i][j] = scan.nextInt();
}
}
for(int i = 1 ; i < 5 ; i++){
for(int j = 1 ; j < 5 ; j++){
if(maxHourGlassValue < currMax){
maxHourGlassValue = currMax;
}
}
}
System.out.println(maxHourGlassValue);
}
}
我只能运行8个测试用例中的6个。有什么可能出错???是吗?
最佳答案
试试这段代码,我没有写那段代码,我只是复制它并从here修改它。
import java.util.Scanner;
public class Test {
public static void main(String ... args){
Scanner scan = new Scanner(System.in);
int size = 6;
int[][] m = new int[size][size];
//numbers input
for(int i=0; i<size; i++)
{
for(int j=0; j<size; j++)
{
m[i][j] = scan.nextInt();
}
}
int temp = 0, MaxSum = -99999;
for (int i=0; i<size; ++i) {
for (int j=0; j<size; ++j) {
if (j+2 < size && i+2 < size) {
temp = m[i][j] + m[i][j+1] + m[i][j+2] + m[i+1][j+1] + m[i+2][j] + m[i+2][j+1] + m[i+2][j+2];
if (temp >= MaxSum) {
MaxSum = temp;
}
}
}
}
System.out.println(MaxSum);
}
}
关于java - 沙漏算法无法获得精确的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40763644/