What is wrong with my code?


  • 0
    S

    Some how I failed the last test case. This works with 43 / 44 cases.

    public class Solution {
        public int calculateMinimumHP(int[][] dungeon) {
            
            // Temp variables for row and column of the dungeon
            int row = dungeon.length;
            int col = dungeon[0].length;
            
            // Create two addition matrix, one for negativeHealth, the other for momentHealth
            int[][] negativeHealth = new int[row][col];
            int[][] momentHealth = new int[row][col];
            
            // Initialize some temporary variables
            int tempHealthUp;
            int tempHealthLeft;
            int negativeHealthUp;
            int negativeHealthLeft;
            // Make a for loop to calculate negativeHealth and the momentHealth
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    if (i == 0 && j == 0) {
                        momentHealth[i][j] = dungeon[i][j];
                        negativeHealth[i][j] = dungeon[i][j];
                    } else if (i == 0) {
                        momentHealth[i][j] = momentHealth[i][j-1] + dungeon[i][j];
                        negativeHealth[i][j] = min(negativeHealth[i][j-1], momentHealth[i][j]);
                    } else if (j == 0) {
                        momentHealth[i][j] = momentHealth[i-1][j] + dungeon[i][j];
                        negativeHealth[i][j] = min(negativeHealth[i-1][j], momentHealth[i][j]);
                    } else {
                        // Most optimal in terms of biggest health
                        tempHealthUp = momentHealth[i-1][j] + dungeon[i][j];
                        tempHealthLeft = momentHealth[i][j-1] + dungeon[i][j];
                        momentHealth[i][j] = max(tempHealthUp,tempHealthLeft);
                        
                        // Most optimal in terms of minimum health
                        negativeHealthUp = min(negativeHealth[i-1][j], tempHealthUp);
                        negativeHealthLeft = min(negativeHealth[i][j-1], tempHealthLeft);
                        negativeHealth[i][j] = max(negativeHealthUp,negativeHealthLeft);
                    }
                }
            }
            return max(1,-negativeHealth[row-1][col-1] + 1);
        }
        
        private int min(int a, int b) {
            if (a<b) return a;
            else return b;
        }
        
        private int max(int a, int b) {
            if (a>b) return a;
            else return b;
        }
    }

  • 0
    I

    @sonmanutd maybe you can post the input of the wrong case


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.