# An easy to understand solution in JAVA

• Calculate the area of each rectangle at first. Judge whether they have intersection. If not, return the sum area of them. Otherwise, count the intersection area and subtract it by one time of total area.

``````public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int rectOne = (C - A) * (D - B);
int rectTwo = (G - E) * (H - F);

if(A >= G || B >= H || C <= E || D <= F){
return rectOne + rectTwo;
}

int length = Math.min(C, G) - Math.max(A, E);
int height = Math.min(D, H) - Math.max(B, F);

return rectOne + rectTwo - length * height;
}
}``````

• my C++ solution is semilar to yours:

``````    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int w = min(C, G) - max(A, E);
int h = min(D, H) - max(B, F);
return (C - A) * (D - B) + (G - E)*(H - F) - (w <= 0 || h <= 0? 0 : w*h);
}``````

• Wrong Answer
Input: -2, -2, 2, 2, -3, 3, -4, 4
Output: 15
Expected: 17
(Maybe OJ got some problems)

• I don't think this is a proper test case. In my point of view, Point (A,B) should be the bottom left corner of a rectangle, etc. So the test case should be -2, -2, 2, 2, -4, 3, -3, 4 which output is 17 under my code.

• Identical approach, slightly more compact code:

``````public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int hOverlap = (H<=B || F>=D)? 0 : Math.min(D,H)-Math.max(F,B);
int vOverlap = (G<=A || E>=C)? 0 : Math.min(C,G)-Math.max(E,A);
return (C-A)*(D-B)+(G-E)*(H-F)-hOverlap*vOverlap;
}
}``````

• This will overflow and return wrong answer. For example min(C, G) < 0 and max(A, E) < 0 and they are both very small.

• @danyang3 I'm curious what's the problem of OJ? I didn't see anything wrong about this test case.

• same idea, similar solution.

``````    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int area = (C-A)*(D-B) + (G-E)*(H-F);
if(E>C || F>D || G < A || H<B)	//要考虑不相交情况
return area;

int bx = Math.max(A, E);
int by = Math.max(B, F);
int tx = Math.min(C, G);
int ty = Math.min(D, H);

return area - (tx-bx)*(ty-by);
}
``````

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