Problem
You are given a 2D integer array stockPrices
where stockPrices[i] = [dayi, pricei]
indicates the price of the stock on day dayi
is pricei
. 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 theminimum number of lines needed to represent the line chart.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= stockPrices.length <= 10^5
stockPrices[i].length == 2
1 <= dayi, pricei <= 10^9
- All
dayi
are distinct.
Solution
Method 1 – Slope Comparison with Sorting
Intuition
To minimize the number of lines, we need to count how many times the slope between consecutive points changes. If the slope remains the same, the points are collinear and can be represented by a single line.
Approach
- Sort the points by day (x-coordinate).
- Iterate through the sorted points and compare the slope between each pair of consecutive segments.
- If the slope changes, increment the line count.
- Return the total number of lines needed.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
, where n is the number of points. Sorting dominates. - 🧺 Space complexity:
O(1)
, only a few variables are used for tracking the answer.