Skip to content

Commit 2e10b45

Browse files
authored
Problem Difficulty Level: Medium
1 parent 19a8d88 commit 2e10b45

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*--------------------------
2+
Time Complexity: O(nlogn)
3+
Space Complexity: O(1)
4+
----------------------------*/
5+
6+
class Solution {
7+
public:
8+
int checkEqualArea(vector<vector<int>> &squares, double splitLine) {
9+
double downArea = 0, upArea = 0;
10+
11+
for (auto &square : squares) {
12+
double bottom = square[1];
13+
double top = bottom + square[2];
14+
double area = (double)square[2] * (double)square[2];
15+
16+
if (top <= splitLine) downArea += area;
17+
else if (bottom >= splitLine) upArea += area;
18+
else {
19+
upArea += (top - splitLine) * square[2];
20+
downArea += (splitLine - bottom) * square[2];
21+
}
22+
}
23+
24+
if (upArea - downArea < 1e-5) return 1;
25+
return (upArea > downArea) ? 0 : -1;
26+
}
27+
28+
double separateSquares(vector<vector<int>>& squares) {
29+
double low = 1e9, high = -1e9;
30+
31+
for (auto &square : squares) {
32+
low = min(low, (double)square[1]);
33+
high = max(high, (double)(square[1] + square[2]));
34+
}
35+
36+
double ans = -1;
37+
while (high - low > 1e-5) {
38+
double mid = low + (high - low) / 2;
39+
int decision = checkEqualArea(squares, mid);
40+
41+
if (decision == 1) {
42+
ans = mid;
43+
high = mid;
44+
}
45+
else if (decision == 0) low = mid;
46+
else high = mid;
47+
}
48+
return ans == -1 ? high : ans;
49+
}
50+
};
51+
52+
/*
53+
Question Link: https://leetcode.com/problems/separate-squares-i/
54+
Author: M.R.Naganathan
55+
*/

0 commit comments

Comments
 (0)