Problem 122

Abstract / Summary

Buy and sell whenever there is a price increase to maximize profit.

Note

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

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
8 lines | 258 bytes | submitted August 21, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 71% (4+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Greedy
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 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 prices contains zero or one element, the range(1, len(prices)) produces an empty sequence, the loop body never executes, and total remains 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 change is non-positive. The conditional if change > 0 prevents any addition to total, resulting in a final profit of zero, which aligns with the optimal strategy of not trading.

  • Constant Prices: When all prices are identical, each change equals zero. The condition excludes these neutral changes, leaving total unchanged 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 > 0 is 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 change directly 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.

written by openai gpt

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.

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 = 8 | μ = 8.52 | σ = 0.83

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 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++
56 links | 39 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Best Time to Buy and Sell a Stock II - Leetcode 122 - Python'
NeetCode 7 mins
Best Time to Buy and Sell a Stock II - Leetcode 122 - Python
YouTube video 'Best Time to Buy and Sell Stock II | Live Coding with Explanation | Leetcode - 122'
Algorithms Made Easy 5 mins
Best Time to Buy and Sell Stock II | Live Coding with Explanation | Leetcode - 122
YouTube video 'Best Time to Buy and Sell Stock II - Leetcode 122 - Arrays & Strings (Python)'
Greg Hogg 10 mins
Best Time to Buy and Sell Stock II - Leetcode 122 - Arrays & Strings (Python)
YouTube video 'LeetCode Tutorial 122. Best Time to Buy and Sell Stock II'
GoodTecher 6 mins
LeetCode Tutorial 122. Best Time to Buy and Sell Stock II
YouTube video 'Best Time to Buy and Sell Stock II - LeetCode 122 - Python #leetcode #greedy'
Deepti Talesra 10 mins
Best Time to Buy and Sell Stock II - LeetCode 122 - Python #leetcode #greedy
YouTube video 'LeetCode 122 | Best Time to Buy and Sell Stock II | Solution Explained (Java + Whiteboard)'
Xavier Elon 7 mins
LeetCode 122 | Best Time to Buy and Sell Stock II | Solution Explained (Java + Whiteboard)
YouTube video '[Java] Leetcode 122. Best Time to Buy and Sell Stock II [DP Decision Making #2]'
Eric Programming 12 mins
[Java] Leetcode 122. Best Time to Buy and Sell Stock II [DP Decision Making #2]
YouTube video 'Best Time to Buy and Sell Stock II | LeetCode 122 | Java'
Tech Tutor 9 mins
Best Time to Buy and Sell Stock II | LeetCode 122 | Java
YouTube video 'best time to buy and sell stock ii | best time to buy and sell stock II leetcode | leetcode 122'
Naresh Gupta 9 mins
best time to buy and sell stock ii | best time to buy and sell stock II leetcode | leetcode 122
YouTube video 'Best Time to Buy and Sell Stock II | Leetcode 122 | Live coding session | DP 🔥🔥🔥'
Coding Decoded 8 mins
Best Time to Buy and Sell Stock II | Leetcode 122 | Live coding session | DP 🔥🔥🔥
YouTube video 'Leetcode | Top Interview 150 | Medium | 122. Best Time to Buy and Sell Stock II | Javascript'
Software Interviews Prep 9 mins
Leetcode | Top Interview 150 | Medium | 122. Best Time to Buy and Sell Stock II | Javascript
YouTube video '122. Best Time to Buy and Sell Stock II | Leetcode Medium | C++| Java| Python | Javascript'
Komal Pal 7 mins
122. Best Time to Buy and Sell Stock II | Leetcode Medium | C++| Java| Python | Javascript
YouTube video 'Daily Leetcode #589: Nov 10, 2021 - 122. Best Time to Buy and Sell Stock II'
Programming Live with Larry 7 mins
Daily Leetcode #589: Nov 10, 2021 - 122. Best Time to Buy and Sell Stock II
YouTube video 'LeetCode 122: Best Time to Buy and Sell Stock II | Java Solution | Greedy Approach'
Code Scribbler 5 mins
LeetCode 122: Best Time to Buy and Sell Stock II | Java Solution | Greedy Approach
YouTube video 'LeetCode 122: Best Time to Buy and Sell Stock II | C# Solution | Greedy Approach'
Code Scribbler 5 mins
LeetCode 122: Best Time to Buy and Sell Stock II | C# Solution | Greedy Approach
YouTube video 'Leetcode 122. Best Time to Buy and Sell Stock II'
Algorithms Casts 18 mins
Leetcode 122. Best Time to Buy and Sell Stock II
YouTube video '122. Best Time to Buy and Sell Stock II (Leetcode Easy)'
Programming Live with Larry 13 mins
122. Best Time to Buy and Sell Stock II (Leetcode Easy)
YouTube video 'Leetcode 122. Best Time to Buy and Sell Stock II - compute differencing array and sum positive diff'
Code-Yao 8 mins
Leetcode 122. Best Time to Buy and Sell Stock II - compute differencing array and sum positive diff
YouTube video 'Facebook Coding Interview Question | Leetcode 122 | Best Time to Buy and Sell Stock II'
WorkWithGoogler 4 mins
Facebook Coding Interview Question | Leetcode 122 | Best Time to Buy and Sell Stock II
YouTube video '122. Best Time to Buy and Sell Stock II'
Math Geeks 5 mins
122. Best Time to Buy and Sell Stock II
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

9 solutions   August 21, 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