JPMORGAN Coding Question β Solved
Determine the highest value after executing n steps on an infinite 2D grid that initially contains all zeros. The grid is indexed from (1,1) at the bottom-left corner with coordinates increasing upwards and to the right.
For each given coordinate pair (r, c), increment every cell in the rectangle from (1,1) to (r,c) inclusive by 1. After processing all coordinates, return the number of cells that contain the maximum value in the grid.
Example:
`upRight = ["1 4", "2 3", "4 1"]`
Each string contains two space-separated integers representing the row (r) and column (c).
The process:
- Step 1: Increment cells in rectangle (1,1) to (1,4)
- Step 2: Increment cells in rectangle (1,1) to (2,3)
- Step 3: Increment cells in rectangle (1,1) to (4,1)
The overlapping region across all three rectangles is the intersection of:
- Rows: min(1, 2, 4) = 1
- Columns: min(4, 3, 1) = 1
Thus, cell (1,1) is the only cell included in all three updates. So the max value in the grid is 3, and it occurs once.
Output: `1`
Function Description:
Complete the function `countMax` in the editor below.
`countMax` has the following parameter:
- `string upRight[n]`: an array of strings where each contains two space-separated integers representing the up-right corner of a rectangle.
Return:
- `long`: the number of occurrences of the final grid's maximum value.
Constraints:
- 1 β€ n β€ 100
- 1 β€ number of rows, number of columns β€ 10^6
Sample Input:
`upRight = ["2 3", "3 7", "4 1"]`
In this case:
- Minimum of rows = min(2, 3, 4) = 2
- Minimum of columns = min(3, 7, 1) = 1
So the overlapping region is of size `2 Γ 1 = 2`
Output: `2`
Asked in:
JPMORGAN