Leetcode 121: Best Time to Buy and Sell Stock

grid47
grid47
Exploring patterns and algorithms
Oct 25, 2024 5 min read

A soft, glowing chart of stock prices with a smooth line representing the best time to buy and sell.
Solution to LeetCode 121: Best Time to Buy and Sell Stock Problem

You are given an array of prices where prices[i] represents the price of a stock on the i-th day. You want to maximize your profit by buying the stock on one day and selling it on a future day. Return the maximum profit you can achieve from this transaction. If no profit can be made, return 0.
Problem
Approach
Steps
Complexity
Input: The input consists of an array prices where prices[i] is the price of the stock on the i-th day.
Example: Input: prices = [10, 3, 15, 8, 12, 5]
Constraints:
• 1 <= prices.length <= 10^5
• 0 <= prices[i] <= 10^4
Output: Return a single integer representing the maximum profit you can achieve from buying and selling the stock.
Example: Output: 9
Constraints:
• The profit should be the difference between the selling price and the buying price, where the selling day is after the buying day.
Goal: The goal is to maximize the profit by choosing the best day to buy and the best day to sell in the future.
Steps:
• Start by initializing the lowest price (l) as the price of the first day.
• Iterate through the prices and update the lowest price (l) as the minimum price encountered so far.
• For each price, calculate the potential profit by subtracting the lowest price (l) from the current price.
• Keep track of the maximum profit (g) encountered during the iteration.
• Return the maximum profit after processing all prices.
Goal: The problem constraints ensure that the input array will contain at least one price and that all prices will be valid within the specified range.
Steps:
• 1 <= prices.length <= 10^5
• 0 <= prices[i] <= 10^4
Assumptions:
• The input array prices contains valid values with at least one price.
Input: Input: prices = [10, 3, 15, 8, 12, 5]
Explanation: The maximum profit can be achieved by buying the stock on day 2 (price = 3) and selling it on day 3 (price = 15). The profit is 15 - 3 = 12.

Input: Input: prices = [7, 6, 4, 3, 1]
Explanation: In this case, no profit can be made as prices keep decreasing, so the maximum profit is 0.

Link to LeetCode Lab


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