2
\$\begingroup\$

In a 2-dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well.

In the end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city's skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example.

What is the maximum total sum that the height of the buildings can be increased?

Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation: 
The grid is:
[ [3, 0, 8, 4], 
  [2, 4, 5, 7],
  [9, 2, 6, 3],
  [0, 3, 1, 0] ]

The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]

The grid after increasing the height of buildings without affecting skylines is:

gridNew = [ [8, 4, 8, 7],
            [7, 4, 7, 7],
            [9, 4, 8, 7],
            [3, 3, 3, 3] ]

Notes:
  • 1 < grid.length = grid[0].length <= 50.

  • All heights grid[i][j] are in the range [0, 100].

  • All buildings in grid[i][j] occupy the entire grid cell: that is, they are a 1 x 1 x grid[i][j] rectangular prism.

My approach:

class Solution {
    public int maxIncreaseKeepingSkyline(int[][] grid) {

        int nrows = grid.length;
        int ncols = grid[0].length;

        int [] leftRig = new int[nrows];
        int [] topBot = new int[ncols];

        //Filling topBot
        for( int i = 0; i < ncols; i++ )
        {
               int max = Integer.MIN_VALUE;    

                for( int j = 0; j < nrows; j++ )
               {
                   if( max <= grid[j][i] )
                       max = grid[j][i];
               }
            topBot[i] = max;
        }

        //Filling leftRig
        for( int k = 0; k < nrows; k++ )
        {
               int max = Integer.MIN_VALUE;    

                for( int l = 0; l < ncols; l++ )
               {
                   if( max <= grid[k][l] )
                       max = grid[k][l];
               }
            leftRig[k] = max;
        }

        int count = 0;
        int min = 0;

        //Enumerating the minimum height to be added
        for( int i = 0; i < nrows; i++ )
        {       
          for( int j = 0; j < ncols; j++ )
            {
                  min = Math.min(leftRig[i],topBot[j]);
                  count += min - grid[i][j];
            }
        }

        return count;
    }
}

Time complexity: O(n^2)

Space complexity: O(n)

Time complexity: O(n) Space complexity: O(n)

I have the following questions regarding the above code snippets:

1) How can I improve the time and space complexity of my code?

2) Is there a better way(lesser lines of code, better data structures) that can be used to improve the code?

3) Is there any better approach to solve this question?

Reference

\$\endgroup\$
  • \$\begingroup\$ Isn't the time complexity O(n)? Because the algorithm works on a given amount of buildings, and you simply iterate over each building a couple of times? \$\endgroup\$ – Koekje May 3 '18 at 11:48
  • \$\begingroup\$ @Koekje, I think the complexity is O(n^2) as there is a nested loop to check the minimum of the leftRig(i) andtopBot(j). \$\endgroup\$ – Anirudh Thatipelli May 3 '18 at 15:16
  • \$\begingroup\$ But a nested loop does not necessarily mean an increase in complexity. What does n represent in your problem? I would say, the amount of buildings. Each nested loop iterates all buildings. So I would say you do around 3n operations, which is still linear w.r.t. the input. If I am not mistaken! \$\endgroup\$ – Koekje May 3 '18 at 15:32
  • \$\begingroup\$ You can see it as either O(n) with n = the number of buildings. Or O(r * c) with r = number of rows and c = number of columns. Both are the same complexity. \$\endgroup\$ – Imus May 4 '18 at 11:36
  • \$\begingroup\$ Since you need to look at all the buildings and save them for that purpose, there is no way to reduce the running time or space complexity under O(n). (Assuming n is amount of buildings) You can reduce the constants a bit as Stingy suggested. Also I commented there you can flip his loops for even better traversal speed. But all in all O(n) is the best you can do. \$\endgroup\$ – findusl May 4 '18 at 12:25
2
\$\begingroup\$
  • Here:

    for( int i = 0; i < ncols; i++ )
    {
        int max = Integer.MIN_VALUE;
    
        for( int j = 0; j < nrows; j++ )
        {
            if( max <= grid[j][i] )
                max = grid[j][i];
        }
        topBot[i] = max;
    }
    

    You don't need an extra variable max as a reference. You can simply use topBot[i] as a reference instead (the elements of an int array will be initialized to the default value 0 upon the array's creation, and since the height of a building cannot be less than 0, 0 is an adequate initial value). Also, it would suffice to check if(max < grid[j][i]) (i.e. using < instead of <=), because you don't need to assign the variable if the two values are equal. In fact, there's an even more concise way to write this:

    topBot[i] = Math.max(topBot[i], grid[j][i]);
    

    And with the local variable max eliminated, you can fill both topBot and leftRig in one loop:

    for (int i = 0; i < ncols; i++) {
        for (int j = 0; j < nrows; j++) {
            topBot[i] = Math.max(topBot[i], grid[j][i]);
            leftRig[j] = Math.max(leftRig[j], grid[j][i]);
        }
    }
    
  • In your final loop, min is not needed outside the inner for loop, so it would suffice to declare it inside this inner loop. Reducing the scope of variables to the smallest extent necessary makes code easier to read, because, in this case, it would make it instantly obvious that the variable is not needed outside the loop.

\$\endgroup\$
  • \$\begingroup\$ Thanks, @Stingy. I will make these changes. Coming back to your previous point, won't keeping the variables max and min improve the understandability of the code? Beginner question. \$\endgroup\$ – Anirudh Thatipelli May 3 '18 at 15:18
  • \$\begingroup\$ @AnirudhThatipelli I suppose you mean keeping the variable max, since min is kept in my suggestion, it's just that its declaration would be moved. It's true that, sometimes, introducing a local variable can increase readability because the name of a variable can serve as documentation. However, in this case, the final value of the local variable is stored without modification in a different variable, namely in an array element, so if readability is a concern, I would instead suggest renaming the variables leftRig and topBot to something like maxHeightInRow and maxHeightInColumn. \$\endgroup\$ – Stingy May 3 '18 at 15:37
  • \$\begingroup\$ Thanks for the clarification, @Stingy. I will keep this in mind. \$\endgroup\$ – Anirudh Thatipelli May 4 '18 at 2:06
  • \$\begingroup\$ in the combined topBot - leftRig loops it's not really clear how it works. This might improve if you rename the loop variables to row and col(or column) instead. Renaming leftRig and topBot as you suggest in your previous comment is also a big improvement. \$\endgroup\$ – Imus May 4 '18 at 11:30
  • \$\begingroup\$ I would suggest flipping the two loops, since accessing all elements in grid[j] before going to grid[j+1] can be faster. See here: dzone.com/articles/2-d-array-traversal \$\endgroup\$ – findusl May 4 '18 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.