Skip to content

Commit e966a67

Browse files
authored
Create minimum-lines-to-represent-a-line-chart.py
1 parent dac3d2b commit e966a67

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Time: O(nlogn)
2+
# Space: O(1)
3+
4+
# sort, math, gcd
5+
class Solution(object):
6+
def minimumLines(self, stockPrices):
7+
"""
8+
:type stockPrices: List[List[int]]
9+
:rtype: int
10+
"""
11+
def gcd(a, b):
12+
while b:
13+
a, b = b, a%b
14+
return a
15+
16+
stockPrices.sort()
17+
result = 0
18+
prev = None
19+
for i in xrange(1, len(stockPrices)):
20+
dy, dx = stockPrices[i][1]-stockPrices[i-1][1], stockPrices[i][0]-stockPrices[i-1][0]
21+
g = gcd(dy, dx)
22+
if not prev or prev != (dy//g, dx//g):
23+
prev = (dy//g, dx//g)
24+
result += 1
25+
return result

0 commit comments

Comments
 (0)