Best Time to Buy and Sell Stock DSA Solution - Study Chapter | QuizMaker

Best Time to Buy and Sell Stock explained with brute force, one-pass greedy optimization, dry run, edge cases, complexity, and Python, C++, Java code.

Read
9m
Type
Chapter
Access
Free

Course

DSA Course: Interview Patterns and Problem Solving

Topic

Module 1: Arrays

Learning Outcome

After this lesson, you should be able to convert the "choose buy and sell days" brute force into a one-pass greedy scan.

Problem Statement

Given prices, where prices[i] is the stock price on day i, return the maximum profit from one buy and one later sell. If no profit is possible, return 0.

InputOutputWhy
[7, 1, 5, 3, 6, 4]5Buy at 1, sell at 6.

Brute Force Approach

Try every buy day and every later sell day. Compute prices[sell] - prices[buy] and keep the best profit.

This checks the rule correctly, but it costs O(n^2) because every day can be paired with many later days.

Optimized Approach

While scanning left to right, keep the minimum price seen so far. If you sell today, the best valid buy day must be one of the earlier days, so today profit is price - minPrice.

This works because every sell day only needs the cheapest earlier buy day, not all earlier days.

Exact Pseudocode

minPrice = infinity
best = 0
for price in prices:
  minPrice = min(minPrice, price)
  best = max(best, price - minPrice)
return best

Reference Code

class Solution:
    def maxProfit(self, prices):
        min_price = float("inf")
        best = 0

        for price in prices:
            min_price = min(min_price, price)
            best = max(best, price - min_price)

        return best
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int minPrice = INT_MAX;
        int best = 0;

        for (int price : prices) {
            minPrice = min(minPrice, price);
            best = max(best, price - minPrice);
        }

        return best;
    }
};
class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int best = 0;

        for (int price : prices) {
            minPrice = Math.min(minPrice, price);
            best = Math.max(best, price - minPrice);
        }

        return best;
    }
}

Sample Dry Run

priceminPriceprofit if sold todaybest
7700
1100
5144
3124
6155
4135

Complexity

MeasureValueReason
TimeO(n)One scan over all prices.
SpaceO(1)Only two variables are stored.

Edge Cases

Interview Checklist

FAQs

Why is this greedy?

For each sell day, the best decision only depends on the cheapest valid buy day seen before it.

Can I sell before buying?

No. The left-to-right scan enforces that the buy price comes from an earlier day.

What if all prices fall?

The best profit remains 0.

Tags

Open on QuizMaker