Leetcode 2280: Minimum Lines to Represent a Line Chart

grid47
grid47
Exploring patterns and algorithms
Mar 24, 2024 6 min read

You are given a list of stock prices where each element represents the stock price on a specific day. The stock prices are given as pairs where the first element is the day number and the second element is the stock price for that day. A line chart can be drawn by plotting these prices on an XY-plane, where the X-axis represents the day and the Y-axis represents the price. Your task is to determine the minimum number of lines required to represent the stock prices as a continuous line chart.
Problem
Approach
Steps
Complexity
Input: The input is a 2D array `stockPrices` where each element `stockPrices[i] = [day_i, price_i]` represents the stock price on `day_i` with a price of `price_i`.
Example: Input: stockPrices = [[1, 10], [2, 15], [3, 12], [4, 18], [5, 20]]
Constraints:
• 1 <= stockPrices.length <= 10^5
• stockPrices[i].length == 2
• 1 <= day_i, price_i <= 10^9
• All day_i are distinct.
Output: The output is an integer representing the minimum number of lines needed to represent the stock price chart.
Example: Output: 2
Constraints:
Goal: The goal is to calculate the minimum number of straight lines that can connect all the stock prices by determining if the points lie on the same straight line.
Steps:
• Sort the stock prices by the day.
• Iterate through the stock prices and check if each consecutive pair lies on the same line as the previous pair.
• If a new line is required, increment the count.
Goal: The solution needs to handle up to 100,000 stock prices efficiently.
Steps:
Assumptions:
• Stock prices will be provided in unsorted order, so sorting is required.
Input: Input: stockPrices = [[1, 7], [2, 6], [3, 5], [4, 4], [5, 4], [6, 3], [7, 2], [8, 1]]
Explanation: The stock prices need 3 lines to be represented. The first line connects points (1, 7) to (4, 4). The second line connects (4, 4) to (5, 4), and the third line connects (5, 4) to (8, 1).

Input: Input: stockPrices = [[1, 3], [2, 5], [3, 7], [4, 9], [5, 11]]
Explanation: The stock prices form a single line where the price increases uniformly. Therefore, only one line is needed to represent the chart.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus