Minimum Lines to Represent a Line Chart - Problem

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.

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

Input & Output

Example 1 — Basic Case
$ Input: stockPrices = [[1,7],[2,6],[3,5]]
Output: 1
💡 Note: All three points lie on the same line with slope -1. From (1,7) to (2,6): slope = (6-7)/(2-1) = -1. From (2,6) to (3,5): slope = (5-6)/(3-2) = -1. Since slopes are the same, only 1 line is needed.
Example 2 — Slope Change
$ Input: stockPrices = [[1,7],[2,6],[3,5],[5,4]]
Output: 3
💡 Note: Three different slopes: (1,7)→(2,6) has slope -1, (2,6)→(3,5) has slope -1, but (3,5)→(5,4) has slope -0.5. Since the slope changes twice, we need 3 separate line segments.
Example 3 — Two Points
$ Input: stockPrices = [[3,4],[1,2]]
Output: 1
💡 Note: Only two points, so exactly one line segment 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
Stock Price Line Chart: Minimum Line SegmentsDay →Price →(1,7)(2,6)(3,5)(4,5.5)(5,6)Line 1Line 2Result2 linesSlope change at (3,5)
Understanding the Visualization
1
Input Points
Stock prices plotted as (day, price) coordinates
2
Connect Points
Connect adjacent points and identify slope changes
3
Count Lines
Each slope change requires a new line segment
Key Takeaway
🎯 Key Insight: Count slope changes between consecutive point pairs to find minimum line segments needed
Asked in
Meta 15 Amazon 12 Google 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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