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
- 32 lines of Java from the credited upstream file 2280.java.
- 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 int minimumLines(int[][] stockPrices) {3 int ans = 0;4 5 Arrays.sort(stockPrices, Comparator.comparingInt(stockPrice -> stockPrice[0]));6 7 for (int i = 2; i < stockPrices.length; ++i) {8 Pair<Integer, Integer> a = getSlope(stockPrices[i - 2], stockPrices[i - 1]);9 Pair<Integer, Integer> b = getSlope(stockPrices[i - 1], stockPrices[i]);10 if (a.getKey() != b.getKey() || a.getValue() != b.getValue())11 ++ans;12 }13 14 return ans + (stockPrices.length > 1 ? 1 : 0);15 }16 17 private Pair<Integer, Integer> getSlope(int[] p, int[] q) {18 final int dx = p[0] - q[0];19 final int dy = p[1] - q[1];20 if (dx == 0)21 return new Pair<>(0, p[0]);22 if (dy == 0)23 return new Pair<>(p[1], 0);24 final int d = gcd(dx, dy);25 return new Pair<>(dx / d, dy / d);26 }27 28 private int gcd(int a, int b) {29 return b == 0 ? a : gcd(b, a % b);30 }31}32