Minimum Lines to Represent a Line Chart Problem
Description
LeetCode Problem 2280.
You are given a 2D integer array stockPrices where stockPrices[i] = [day_i, price_i] indicates the price of the stock on day day_i is price_i. A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below:

Return the minimum number of lines needed to represent the line chart.
Example 1:

Input: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]]
Output: 3
Explanation:
The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price.
The following 3 lines can be drawn to represent the line chart:
- Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4).
- Line 2 (in blue) from (4,4) to (5,4).
- Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1).
It can be shown that it is not possible to represent the line chart using less than 3 lines.
Example 2:

Input: stockPrices = [[3,4],[1,2],[7,8],[2,3]]
Output: 1
Explanation:
As shown in the diagram above, the line chart can be represented with a single line.
Constraints:
1 <= stockPrices.length <= 10^5stockPrices[i].length == 21 <= day_i, price_i <= 10^9- All
day_iare distinct.
Solution
Approach: Sort and Compare Slopes
Sort the points by day. Consecutive points are joined by a segment, and two neighbouring segments need only one line when they have the same slope. So the answer is the number of segments whose slope differs from the previous segment's slope, counting the first segment.
Compare slopes without division, to avoid floating-point error. For segments (dx1, dy1) and (dx2, dy2) the slopes are equal exactly when dy1 * dx2 == dx1 * dy2. The differences can reach 10^9, so the products need 64-bit integers.
Start with a fictitious previous segment (dx, dy) = (0, 1) so the first real segment always counts as a new line. A single point gives 0 lines.
Complexity: O(n log n) time for the sort and O(1) extra space besides it.
class Solution:
def minimumLines(self, stockPrices: List[List[int]]) -> int:
stockPrices.sort()
dx, dy = 0, 1
ans = 0
for i in range(1, len(stockPrices)):
x, y = stockPrices[i - 1]
x1, y1 = stockPrices[i]
dx1, dy1 = x1 - x, y1 - y
if dy * dx1 != dx * dy1:
ans += 1
dx, dy = dx1, dy1
return ans