-
Notifications
You must be signed in to change notification settings - Fork 3
/
RectangleArea223.kt
47 lines (33 loc) · 1.23 KB
/
RectangleArea223.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package medium
/**
* Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.
The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).
The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).
Example 1:
Rectangle Area
Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
Output: 45
Example 2:
Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
Output: 16
Constraints:
-104 <= ax1 <= ax2 <= 104
-104 <= ay1 <= ay2 <= 104
-104 <= bx1 <= bx2 <= 104
-104 <= by1 <= by2 <= 104
*/
fun computeArea(ax1: Int, ay1: Int, ax2: Int, ay2: Int, bx1: Int, by1: Int, bx2: Int, by2: Int): Int {
// Calculate Area of A
val areaA = (ay2 - ay1) * (ax2 - ax1)
// Calculate Area of B
val areaB = (by2 - by1) * (bx2 - bx1)
// Calculate Overlap X
val overlapX = Math.min(ax2, bx2) - Math.max(ax1, bx1)
// Calculate Overlap Y
val overlapY = Math.min(ay2, by2) - Math.max(ay1, by1)
var overlap = 0
if (overlapX > 0 && overlapY > 0) {
overlap = overlapX * overlapY
}
return areaA + areaB - overlap
}