Beats 100% of the solutions - JAVA - explained


  • 1
    V
     public int[] constructRectangle(int area) {
        
        int[] output = new int[2];
    	
    	output[0] = 1;
    	output[1] = area;
    	int length = 0;
    	
    	for (int width = 1; width <= Math.ceil(Math.sqrt(area)); width++) {
    		
    		length = area/width;
    		
    		if ((length * width) == area && Math.abs(length - width) <= Math.abs(output[0] - output[1]) && length >= width) {
    			output[0] = length;
    			output[1] = width;
    		}
    	}
    	
    	return output;
    }
    

    The idea is simple:
    1.) Initialise the output with 1 and area as they are the most prominent factors of a given number.
    2.) Remember, the question simply asks us to factorise a given number such that their difference is minimum.
    3.) We can factorise a given number by simply iterating from 1 to sqrt(n)
    4.) Divide area by each number while looping to get length.
    5.) The if condition checks a) whethe if the combination of length and width are area b) whether if the current combination we hold the smallest difference and c) whether if length >= width
    6.) return output


Log in to reply
 

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