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;
}
};
Difficulty
and has an acceptance rate of about 57% (10+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 53: Maximum Subarray
- problem 122: Best Time to Buy and Sell Stock II
- problem 2016: Maximum Difference Between Increasing Elements
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- 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