Python 0122.py
class Solution:
def maxProfit(self, prices: List[int]) -> int:
total = 0
for i in range(1, len(prices)):
change = prices[i] - prices[i-1]
if change > 0:
total += change
return total
Difficulty
and has an acceptance rate of about 71% (4+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Greedy
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 defines a class Solution with a method maxProfit that computes the maximum profit obtainable from a sequence of stock prices. The algorithm iterates through the price list once, accumulating positive day-to-day price differences. By summing only the gains, it effectively captures the total profit achievable through any number of buy-sell transactions without overlapping.
Key Steps
The core of the algorithm consists of three distinct operations: initialization, iteration with change detection, and accumulation of profitable differences.
The initialization creates a variable to hold the running total of profit.
total = 0
The iteration starts from the second element of the prices list, ensuring each price is compared with its immediate predecessor.
for i in range(1, len(prices)):
Within the loop, the change between consecutive days is calculated.
change = prices[i] - prices[i-1]
A conditional check determines whether the change represents a profit. Only positive changes contribute to the total.
if change > 0:
total += change
After processing all price pairs, the method returns the accumulated profit.
return total
Edge Cases Handled
The algorithm gracefully handles several edge conditions without additional branching:
-
Empty or Single-Element Input: When
pricescontains zero or one element, therange(1, len(prices))produces an empty sequence, the loop body never executes, andtotalremains zero. The method correctly returns zero profit, reflecting the impossibility of any transaction. -
Monotonically Decreasing Prices: If each successive price is lower than the previous one, every computed
changeis non-positive. The conditionalif change > 0prevents any addition tototal, resulting in a final profit of zero, which aligns with the optimal strategy of not trading. -
Constant Prices: When all prices are identical, each
changeequals zero. The condition excludes these neutral changes, leavingtotalunchanged and correctly indicating no profit can be made. -
Large Price Fluctuations: The algorithm does not impose any limits on the magnitude of price differences. Positive spikes, regardless of size, are added directly to
total, ensuring the full profit from each upward movement is captured.
Performance Optimizations
The implementation exhibits several implicit performance characteristics:
-
Single Pass Traversal: By iterating once over the input list, the method avoids repeated scans or nested loops. This linear progression minimizes the number of memory accesses and keeps the runtime proportional to the length of the input.
-
In-Place Computation: The algorithm uses only a few scalar variables (
total,i,change) and does not allocate auxiliary data structures such as additional lists or dictionaries. This low memory footprint reduces pressure on the garbage collector and improves cache locality. -
Branch Prediction Friendly: The conditional
if change > 0is a simple comparison that modern CPUs can predict efficiently, especially when price sequences contain clusters of positive or negative changes. This contributes to steady execution speed across varied data patterns. -
Avoidance of Redundant Operations: The calculation of
changedirectly uses the two adjacent elements without intermediate storage or function calls. The immediate use of the result in the conditional eliminates unnecessary temporaries.
Overall, the method delivers a concise and efficient solution for computing maximum achievable profit under the given transaction model.
ELI5 - Simplified Explanation
Imagine you have a collection of magic number cards that change their values every day, and you want to make as much play money as possible. The code starts with a piggy bank that begins empty. It looks at the price of a card today and compares it to the price of the same card from yesterday. If the price today is higher than it was yesterday, it means you caught a little bit of growth. The code takes that extra amount and drops it into the piggy bank. If the price went down or stayed the same, the code simply skips it and moves on to the next day. It does this step by step for every single card until it reaches the end of the line, keeping all the little gains it found along the way.
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 | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | AdelDaniel | Dart | |||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JS | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| martianoff | Scala | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, 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++ | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JavaScript | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| martianoff | Scala | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 121: Best Time to Buy and Sell Stock
- problem 123: Best Time to Buy and Sell Stock III
- problem 309: Best Time to Buy and Sell Stock with Cooldown
- problem 714: Best Time to Buy and Sell Stock with Transaction Fee
Solved On The Same Day
- problem 108: Convert Sorted Array to Binary Search Tree
- problem 482: License Key Formatting
- problem 72: Edit Distance
- problem 167: Two Sum II - Input Array Is Sorted
- problem 453: Minimum Moves to Equal Array Elements
- problem 515: Find Largest Value in Each Tree Row
- problem 535: Encode and Decode TinyURL
- problem 123: Best Time to Buy and Sell Stock III
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