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
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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code