Why do I get wrong answer with my code?


  • 0
    G
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            int s1 = (C-A)*(D-B);
            int s2 = (G-E)*(H-F);
            int dx =0, dy=0;
    
            int h1 = Math.max(A, E);  
            int h2 = Math.min(C, G);  
            dx = h2 - h1;  
              
            int v1 = Math.max(B, F);  
            int v2 = Math.min(D, H);  
            dy = v2 - v1;  
              
            if(dx<=0 || dy<=0) return s1+s2;
            
            return s1+s2-dx*dy;
    }
    

    I couldn't figure out why I get wrong answer here? Any one give me a hand? Thanks!

    Wrong answer with Input:
    -1500000001
    0
    -1500000000
    1
    1500000000
    0
    1500000001
    1

    Output: -1294967294
    Expected: 2


  • 2
    X

    For this test case, there is a overflow problem in your code;

        int h1 = Math.max(A, E);  
        int h2 = Math.min(C, G);  
        dx = h2 - h1;   
        dx will overflow!
    

    So for this case, you need to check there is no overlap first but not calculate dx and use "dx<=0" to determine if there is a overlap.


  • 0
    T

    Validate if h1,h2;v1,v2 gives a valid rectangle as you expect.


Log in to reply
 

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