Approach
Sorting and greedy selection
For Minimum Lines to Represent a Line Chart, 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
- 30 lines of C++ from the credited upstream file 2280.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 int minimumLines(vector<vector<int>>& stockPrices) {4 int ans = 0;5 6 ranges::sort(stockPrices);7 8 for (int i = 2; i < stockPrices.size(); ++i) {9 const pair<int, int> a = getSlope(stockPrices[i - 2], stockPrices[i - 1]);10 const pair<int, int> b = getSlope(stockPrices[i - 1], stockPrices[i]);11 if (a != b)12 ++ans;13 }14 15 return ans + (stockPrices.size() > 1);16 }17 18 private:19 pair<int, int> getSlope(const vector<int>& p, const vector<int>& q) {20 const int dx = p[0] - q[0];21 const int dy = p[1] - q[1];22 if (dx == 0)23 return {0, p[0]};24 if (dy == 0)25 return {p[1], 0};26 const int d = __gcd(dx, dy);27 return {dx / d, dy / d};28 }29};30