Problem 121

Abstract / Summary

Given a list of daily stock prices, find the maximum profit from one buy and one sell.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0121.cpp

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int high = prices[0];
        int low  = prices[0];

        int best = 0;

        for (auto p : prices)
        {
            if (low > p)
            {
                low = p;
                high = p;
            }
            if (high < p)
                high = p;

            if (best < high - low)
                best = high - low;
        }

        return best;
    }
};
25 lines | 483 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (10+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the maximum possible profit from a single buy-sell transaction given a chronological list of stock prices. It iterates through the price array once, maintaining three variables: the lowest price seen so far (low), the highest price observed after that low (high), and the best profit discovered (best). By updating these variables in a single pass, the algorithm derives the optimal profit without revisiting any element.

Key Steps

Initialization

At the start, the algorithm seeds the tracking variables with the first price in the input vector. This ensures that subsequent comparisons have a valid baseline.

int high = prices[0];
int low  = prices[0];
int best = 0;

Iterating Over Prices

A range-based for loop walks through each price p in the vector. The loop body contains three logical sections that adjust the tracking variables.

for (auto p : prices)
{
    // body described below
}

Updating the Minimum Price

When the current price is lower than the stored low, both low and high are reset to this new minimum. Resetting high prevents an outdated high from being paired with a later low, which would otherwise inflate the profit calculation.

if (low > p)
{
    low = p;
    high = p;
}

Extending the Current High

If the current price exceeds the stored high, the algorithm updates high to reflect the new maximum reachable after the current low. This captures the best sell price for the ongoing buy point.

if (high < p)
    high = p;

Recording the Best Profit

After potentially adjusting low and high, the algorithm checks whether the difference high - low surpasses the previously recorded best. If it does, best is updated to the larger profit.

if (best < high - low)
    best = high - low;

Returning the Result

When the loop finishes, best holds the maximum profit achievable with a single transaction, and the function returns this value.

return best;

Edge Cases Handled

The code gracefully manages several boundary conditions without explicit special-case logic.

When the input contains a single price, the loop runs once, low and high remain equal, and best stays at zero, correctly indicating that no profit is possible.

If the price series is strictly decreasing, each new lower price triggers the reset of both low and high. Consequently, high - low never becomes positive, and best remains zero, reflecting the impossibility of a profitable trade.

When all prices are identical, the equality checks (low > p and high < p) never fire, leaving low, high, and best unchanged, again resulting in a zero profit.

The algorithm also tolerates large input sizes because it never accesses indices out of range; all operations rely on the current element p supplied by the range-based loop.

Performance Optimizations

The implementation achieves optimal runtime characteristics by processing the input in a single linear pass. Each price is examined exactly once, and all updates involve only constant-time arithmetic and comparisons.

Memory usage is minimized by storing only three integer variables regardless of the input length, eliminating the need for auxiliary data structures such as auxiliary arrays or stacks.

Resetting high together with low when a new minimum is found prevents unnecessary future comparisons with an obsolete high value, thereby reducing the number of arithmetic operations required to maintain the correct profit window.

The use of a range-based for loop allows the compiler to generate efficient iterator code, often translating to simple pointer arithmetic under the hood, which further contributes to the streamlined execution path.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you are shopping at a store that sells magical toys where the prices change every single day. You want to buy a toy when the price is very small and then wait until a later day to sell it when the price is much bigger so you can keep the extra money as a reward.

The code works by looking at the price list one day at a time. It keeps two special notes in its pocket. One note remembers the lowest price seen so far, and the other note remembers the highest price seen since that low point.

As the code moves through the list of prices, it constantly updates those notes. If it finds a new price that is even cheaper than the one it remembered, it resets its plan because now is a better time to start waiting for a profit. If it finds a price that is higher than what it has seen, it calculates how much money would be made by selling at that new higher price. It keeps track of the biggest amount of money it could make during the whole trip. Once it finishes looking at every single day on the list, it knows exactly how much the best possible profit would be.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.22 | σ = 1.62

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# Java Rust JS Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
63 links | 45 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Best Time to Buy and Sell Stock - Leetcode 121 - Arrays & Strings (Python)'
Greg Hogg 6 mins
Best Time to Buy and Sell Stock - Leetcode 121 - Arrays & Strings (Python)
YouTube video 'Best Time to Buy and Sell Stock | | Leetcode 121 | Love Babbar DSA Sheet | Array | Hindi'
Ayushi Sharma 11 mins
Best Time to Buy and Sell Stock | | Leetcode 121 | Love Babbar DSA Sheet | Array | Hindi
YouTube video 'Best Time To Buy And Sell Stock - LeetCode 121 - JavaScript'
AlgoJS 6 mins
Best Time To Buy And Sell Stock - LeetCode 121 - JavaScript
YouTube video 'Best Time to Buy and Sell Stock V | Made Simple | Detailed | Leetcode 3573 | codestorywithMIK'
codestorywithMIK 41 mins
Best Time to Buy and Sell Stock V | Made Simple | Detailed | Leetcode 3573 | codestorywithMIK
YouTube video 'Best Time to Buy and Sell Stock | Leetcode - 121'
Algorithms Made Easy 13 mins
Best Time to Buy and Sell Stock | Leetcode - 121
YouTube video 'Best Time to Buy and Sell Stock || Leetcode 121 || 1 Variant Question Big Tech Actually Asks'
Coding with Minmer 25 mins
Best Time to Buy and Sell Stock || Leetcode 121 || 1 Variant Question Big Tech Actually Asks
YouTube video 'Best Time to Buy and Sell Stock - Leetcode 121 - Python'
Deepti Talesra 11 mins
Best Time to Buy and Sell Stock - Leetcode 121 - Python
YouTube video '一个视频解决所有Best Time to Buy and Sell Stock问题'
happygirlzt 24 mins
一个视频解决所有Best Time to Buy and Sell Stock问题
YouTube video 'Best Time to Buy and Sell Stock | Leet code 121 | Theory explained + Python code'
Sai Anish Malla 9 mins
Best Time to Buy and Sell Stock | Leet code 121 | Theory explained + Python code
YouTube video 'Best Time to Buy and Sell Stock - LeetCode 121 - Java'
Ali Bouali 11 mins
Best Time to Buy and Sell Stock - LeetCode 121 - Java
YouTube video '[Java] Leetcode 121. Best Time to Buy and Sell Stock [DP Decision Making #1]'
Eric Programming 9 mins
[Java] Leetcode 121. Best Time to Buy and Sell Stock [DP Decision Making #1]
YouTube video '121. Best Time to Buy and Sell Stock | JavaScript | Two Pointers | LeetCode 75 | Daily Challenge'
LeetCodeWithMonu 9 mins
121. Best Time to Buy and Sell Stock | JavaScript | Two Pointers | LeetCode 75 | Daily Challenge
YouTube video 'BEST TIME TO BUY AND SELL STOCK | LEETCODE # 121 | PYTHON SOLUTION'
Cracking FAANG 11 mins
BEST TIME TO BUY AND SELL STOCK | LEETCODE # 121 | PYTHON SOLUTION
YouTube video 'LeetCode 121: Best Time to Buy and Sell Stock | C# Solution | One Pass Approach |'
Code Scribbler 13 mins
LeetCode 121: Best Time to Buy and Sell Stock | C# Solution | One Pass Approach |
YouTube video 'Leetcode 121: Best Time to Buy and Sell Stock in Telugu | Brute Force, Optimal | srkcodes'
Srk Codes 14 mins
Leetcode 121: Best Time to Buy and Sell Stock in Telugu | Brute Force, Optimal | srkcodes
YouTube video '14. Best Time to Buy and Sell Stock | Array - Medium | Learn DSA | Leetcode 121'
Ayushi Sharma 12 mins
14. Best Time to Buy and Sell Stock | Array - Medium | Learn DSA | Leetcode 121
YouTube video '121. Best Time to Buy and Sell Stock || NEETCODE 150'
TechWithSaumya 11 mins
121. Best Time to Buy and Sell Stock || NEETCODE 150
YouTube video 'best time to buy and sell stock leetcode | leetcode 121'
Naresh Gupta 8 mins
best time to buy and sell stock leetcode | leetcode 121
YouTube video '3652. Best Time to Buy and Sell Stock using Strategy (Leetcode Medium)'
Programming Live with Larry 16 mins
3652. Best Time to Buy and Sell Stock using Strategy (Leetcode Medium)
YouTube video 'Best Time To Buy And Sell Stock - Leetcode 121'
Code With K5KC 7 mins
Best Time To Buy And Sell Stock - Leetcode 121
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality