Minimum Lines to Represent a Line Chart - Problem

You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] represents the price of a stock on day dayi.

To create a line chart, you plot these points on an XY plane where:

  • X-axis represents the day
  • Y-axis represents the price

You then connect adjacent points (sorted by day) with straight line segments. Your task is to find the minimum number of lines needed to represent this line chart.

Two consecutive line segments can be merged into one if they have the same slope.

Example: If you have points representing days [1,2,3,4] with prices [1,2,3,2], you would need 2 lines: one from day 1-3 (slope = 1) and another from day 3-4 (slope = -1).

Input & Output

example_1.py โ€” Basic Case
$ Input: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]]
โ€บ Output: 3
๐Ÿ’ก Note: The chart needs 3 lines: from day 1-4 (slope=-1), day 4-5 (slope=0), and day 5-8 (slope=-1). The slope changes at day 4 and day 5, creating 3 distinct line segments.
example_2.py โ€” Single Line
$ Input: stockPrices = [[3,4],[1,2],[7,8],[2,3]]
โ€บ Output: 1
๐Ÿ’ก Note: After sorting by day: [(1,2), (2,3), (3,4), (7,8)]. All consecutive segments have the same slope of 1, so only 1 line is needed.
example_3.py โ€” Minimum Case
$ Input: stockPrices = [[1,1],[500,500000]]
โ€บ Output: 1
๐Ÿ’ก Note: Only two points, so exactly 1 line is needed to connect them.

Constraints

  • 1 โ‰ค stockPrices.length โ‰ค 105
  • stockPrices[i].length == 2
  • 1 โ‰ค dayi, pricei โ‰ค 109
  • All dayi are distinct

Visualization

Tap to expand
Minimum Lines for Stock ChartTime (Days)Price ($)D1D2D3D4D5D6D7Line 1 (Slope: -2/3)Line 2 (Slope: 1/5)Line 3 (Slope: 3/5)Result: 3 lines needed (2 slope changes detected)
Understanding the Visualization
1
Sort by Time
Arrange all stock price points chronologically by day
2
Track Slope Changes
Compare slopes between consecutive point pairs using cross multiplication
3
Count Line Segments
Each slope change indicates the need for a new line segment
Key Takeaway
๐ŸŽฏ Key Insight: Use cross multiplication (dy1ร—dx2 โ‰Ÿ dy2ร—dx1) instead of division to compare slopes and avoid floating point precision errors
Asked in
Microsoft 35 Google 28 Amazon 22 Meta 18
23.9K Views
Medium Frequency
~25 min Avg. Time
756 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen