Best Time to Buy and Sell Stock
Best Time to Buy and Sell Stock
Problem Statement
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.
Example
Input: prices = [7,1,5,3,6,4]
Max Profit: 5
(Buy on Day 2, Sell on Day 5)
Output: 5
Solution
This problem can be solved efficiently using a sliding window approach. We use two pointers, `left` (buy) and `right` (sell), to represent the current window of transactions. We iterate through the prices, updating the maximum profit found so far.
Algorithm Steps
- Initialize `left` pointer to 0, `right` pointer to 1, and `maxProfit` to 0.
- Iterate with the `right` pointer through the `prices` array.
- If `prices[right]` is greater than `prices[left]`, calculate the potential profit. Update `maxProfit` if this profit is higher.
- If `prices[right]` is less than or equal to `prices[left]`, it means we've found a new potential buying point. Move the `left` pointer to the `right` pointer's position.
- Increment the `right` pointer in each iteration to expand the window.
- Return `maxProfit` after the loop finishes.
Best Time to Buy and Sell Stock
Sliding Window Approach
Ready to start the visualization
Stock Prices
Current Profit
Max Profit