Approach
Sorting and greedy selection
For Separate Squares I, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 35 lines of C++ from the credited upstream file 3453.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 double separateSquares(vector<vector<int>>& squares) {4 const double halfArea = accumulate(squares.begin(), squares.end(), 0.0,5 [](double sum, vector<int>& square) {6 return sum + static_cast<long>(square[2]) * square[2];7 }) / 2;8 vector<tuple<int, bool, int>> events;9 10 for (const vector<int>& square : squares) {11 const int y = square[1];12 const int l = square[2];13 events.push_back({y, true, l}); 14 events.push_back({y + l, false, l}); 15 }16 17 ranges::sort(events);18 19 double area = 0;20 int width = 0;21 int prevY = 0;22 23 for (const auto& [y, isStart, l] : events) {24 double areaGain = width * static_cast<long>(y - prevY);25 if (area + areaGain >= halfArea)26 return prevY + (halfArea - area) / width;27 area += areaGain;28 width += isStart ? l : -l;29 prevY = y;30 }31 32 throw;33 }34};35