[LeetCode] Minimum Lines to Represent a Line Chart

2280. Minimum Lines to Represent a Line Chart

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int minimumLines(vector<vector<int>>& s) {
int py = INT_MIN, px = INT_MIN;
sort(begin(s), end(s));
int n = s.size(), res = 0;
for(int i = 0; i < n - 1; i++) {
int dy = s[i + 1][0] - s[i][0];
int dx = s[i + 1][1] - s[i][1];
int gcd = __gcd(dy, dx);
dy /= gcd;
dx /= gcd;
if(dy == py and dx == px) continue;
res++;

py = dy;
px = dx;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/LeetCode/minimum-lines-to-represent-a-line-chart/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.