Idea
- The idea here is that the perimeter of a rectangle must be an even number
2k, wherekis an Integer (整数). Because there are 2 pairs ofheight+widthwhich iskto fit into the definition of even number - Thus, we can return
0straight ifn%2 == 1 - Otherwise, we can obtain
kby dividing the givennby 2 - Remember
kisheight+width, so ifkis10, the possible combination ofheightandwidthis(1,9),(2,8),(3,7),(4,6)and(5,5) - We not including
(6,4)because it is same as(6,4). The order doesn’t matter - We can observe that after the midpoint
5, it starts to repeat itself - So we can conclude that the possible combination of
heightandwidthgivenkisk/2(rounding down) - Since we don’t want square, which means the
heightandwidthare the same →(5,5),k=10, and this can only happen whenk%2 = 0akakcan be split into 2 equal values - Thus, we minus 1 to the final answer if
k%2 = 0
Space & Time Analysis
The analysis method we are using is Algorithm Complexity Analysis
Space - O(1)
- Ignore input size & language dependent space
- We aren’t creating any objects on the Heap Segment
Time - O(1)
- No looping is needed to loop through all possible pairs of
heightandwidthby leveraging on the beauty of counting
Codes
1st Attempt (Java)
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
// Read input data
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int res = 0;
if (n % 2 == 1) {
System.out.println(res);
return;
}
int widthHeight = n/2;
res = widthHeight/2;
if (widthHeight % 2 == 0) res--;
System.out.println(res);
}
}Personal Reflection
- Why it takes so long to solve: simply unfamiliar with combinatorics and failed to make basic deduction that the perimeter of rectangle must be even
- What you could have done better: Practice more combinatorics and read about counting in Discrete Math
- What you missed: perimeter of rectangle must be even and using counting to come out an answer in constant time instead of loop through each possible pair of
heightandwidth - Ideas you’ve seen before: the definition of even number,
2kwherekis an Integer (整数) - Ideas you found here that could help you later: the beauty of counting in combinatorics
- Ideas that didn’t work and why: Looping through each possible pair of
heightandwidth. This takes linear time and it leads to timeout
