#2280

Minimum Lines to Represent a Line Chart

expert · 1205 · lc medium +32 · verified · 26.9% accepted · 366 likes · top 5%

Description

You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] records the stock price on day dayi. When these points are plotted on an XY plane (X = day, Y = price) and adjacent points are connected, the result is a line chart.

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

Example 1:

Input: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]]
Output: 3
Explanation:
The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price.
The following 3 lines can be drawn to represent the line chart:
- Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4).
- Line 2 (in blue) from (4,4) to (5,4).
- Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1).
It can be shown that it is not possible to represent the line chart using less than 3 lines.

Example 2:

Input: stockPrices = [[3,4],[1,2],[7,8],[2,3]]
Output: 1
Explanation:
As shown in the diagram above, the line chart can be represented with a single line.

Code

1
2
3