Problem Description
Given an array stockPrices where each element is a pair [day, price] representing the stock's price on that day, determine the minimum number of straight line segments required to represent the line chart when the points are connected in order of increasing day. A new line segment is needed every time the slope between consecutive points changes.
Key Insights
- Sort the stockPrices based on the day since they may be unsorted.
- Two consecutive points form a continuous line if they maintain the same slope.
- Instead of computing slopes with division (which may lead to precision issues), use cross multiplication on differences to check for collinearity.
- Count segments by incrementing when the current segment's slope differs from the previous segment's slope.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the stockPrices. Space Complexity: O(n) for storing the sorted list.
Solution
Sort the stockPrices by day first. Initialize the line count as 1 (since at least one segment is needed) and use the difference between the first two points to represent the starting slope. Then, iterate over the remaining points and check if each new point is collinear with the current segment by verifying (y3 - y2) * dx equals dy * (x3 - x2) using cross multiplication. If not, increment the segment count and update the slope using the last two considered points.