-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path085-counting-rectangles.js
More file actions
54 lines (41 loc) · 1.22 KB
/
085-counting-rectangles.js
File metadata and controls
54 lines (41 loc) · 1.22 KB
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
48
49
50
51
52
53
54
/**
* Counting Rectangles
* Time Complexity: O(T × √target)
* Space Complexity: O(1)
*/
function processData(input) {
const lines = input.trim().split('\n').map(Number);
let idx = 0;
const T = lines[idx++];
let output = [];
for (let t = 0; t < T; t++) {
const target = lines[idx++];
let bestDiff = Infinity;
let bestArea = 0;
for (let m = 1; ; m++) {
const rectM = (m * (m + 1)) / 2;
if (rectM > target * 2) break;
for (let n = 1; ; n++) {
const rectN = (n * (n + 1)) / 2;
const rectangles = rectM * rectN;
const diff = Math.abs(rectangles - target);
if (diff < bestDiff || (diff === bestDiff && m * n > bestArea)) {
bestDiff = diff;
bestArea = m * n;
}
if (rectangles > target) break;
}
}
output.push(bestArea.toString());
}
console.log(output.join('\n'));
};
process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});