HourGlass模式的最大总和未通过所有测试

时间:2018-10-08 08:56:33

标签: java arrays hourglass

我一直在尝试解决HackerRank, Day11上的问题 但是我编写的代码在提交My submission results之后没有通过所有测试,我不知道为什么会这样,我尝试制作一个Custom Input并且都成功通过了

import java.util.*;

public class Solution {


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

    public static void main(String[] args) {
        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;
            }
        }

        scanner.close();

        /*
        * 
        * Solution start from here
        * 
        * */

        int max = 0;    //store the maximum sum of HourGlass
        int count;      //counter for HourGlass to represent the location at HourGlass, starts at 1 ends at 9
        int sum;        //Store the summation of Hourglass

        //This is the 2D array loop
        for (int k = 0; k <= Math.round(arr.length / 2); k++) {
            for (int l = 0; l <= Math.round(arr.length / 2); l++) {
                count = 0; //initializing the counter
                sum = 0;    //initializing the sum

                //This is the HourGlass Loop
                for (int m = k; m <= k + 2; m++) {
                    for (int n = l; n <= l + 2; n++) {

                        //Prevent adding location 3 and 5 in HourGlass to the summation
                        if (count == 3 || count == 5) {
                            sum += 0;
                        } else {
                            sum += arr[m][n];
                        }
                        count++;    //counter increment to prepare moving to next cell
                    }
                    //Check if the last summation is larger than the previous maximum stored
                    if (sum > max) {
                        max = sum;
                    }
                }


            }
        }

        System.out.println(max);    //Print the result
    }
}

我找到了解决该挑战的方法,但是都使用了不同的算法。问题是我想了解我构建的算法是否存在问题以及如何解决。

0 个答案:

没有答案