Algorithm Day78 - Best Time to Buy and Sell Stock
π§© Problem Description
You are given an array prices where prices[i] is the price of a given stock on the i-th day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
π¬ Examples
Example 1
1 | Input: prices = [7,1,5,3,6,4] |
Example 2
1 | Input: prices = [7,6,4,3,1] |
π‘ Intuition
We want the largest difference prices[j] - prices[i] with j > i.
A simple linear scan can track the minimum price so far and compute the potential profit at each day by subtracting the current min from the current price. Keep the maximum profit encountered. This is a greedy O(n) solution.
π’ Java Code (One-pass Greedy)
1 | class Solution { |
π Alternative (Kadane-like)
You can view the problem as finding the maximum subarray sum of daily differences diff[i] = prices[i] - prices[i-1]. Apply Kadaneβs algorithm to diff to get the same O(n) result.
β± Complexity Analysis
- Time: O(n) β single pass through prices.
- Space: O(1) β constant extra memory.
βοΈ Summary
- Track the minimum buying price so far and update the maximum profit at each step.
- Very efficient greedy solution: O(n) time, O(1) space.
Related problems
lc-122β Best Time to Buy and Sell Stock IIlc-123β Best Time to Buy and Sell Stock IIIlc-188β Best Time to Buy and Sell Stock IV