Minimum Lines to Represent a Line Chart — LeetCode 2280 Python Solution
- Problem
- #2280
- Pattern
- Sorting
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- 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.
Python solution
class Solution:
def minimumLines(self, stockPrices: List[List[int]]) -> int:
stockPrices.sort()
dx, dy = 0, 1
ans = 0
for (x, y), (x1, y1) in pairwise(stockPrices):
dx1, dy1 = x1 - x, y1 - y
if dy * dx1 != dx * dy1:
ans += 1
dx, dy = dx1, dy1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2280. Minimum Lines to Represent a Line Chart is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2280. Minimum Lines to Represent a Line Chart?
- LeetCode 2280. Minimum Lines to Represent a Line Chart is rated Medium on LeetCode.
- What topics does LeetCode 2280. Minimum Lines to Represent a Line Chart cover?
- LeetCode 2280. Minimum Lines to Represent a Line Chart is tagged Geometry, Array, Math, Number Theory and Sorting on LeetCode.