Stock Buy and Sell (Multiple Transactions)
A medium Arrays problem included in Apna College, Love Babbar 450. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Arrays
- Sheets
- 2
- Core for
- 25 roles
- Platform
- LeetCode
The problem
Given an array of daily stock prices, compute the maximum profit achievable by making as many buy-sell transactions as you like, but you can only hold one share at a time.
Example 1
- Input
- [7,1,5,3,6,4]
- Output
- 7
Example 2
- Input
- [1,2,3,4,5]
- Output
- 4
Example 3
- Input
- [7,6,4,3,1]
- Output
- 0
Constraints
- 1 <= n <= 10^4
- 0 <= prices[i] <= 10^4
How to think about it
Updated 2026-09-09Holding across a multi-day price ascent produces the exact same profit as selling and immediately rebuying every single day the price increases: (p[c] - p[a]) equals (p[b] - p[a]) + (p[c] - p[b]). Capturing every positive consecutive price difference guarantees capturing every upward run without ever tracking valleys and peaks explicitly.
Approaches, worst first
Peak-valley traversal
time O(n) · space O(1)
Find local minima (valleys) to buy and subsequent local maxima (peaks) to sell. Accurate and intuitive, but requires multi-condition pointer logic and boundary edge checks to prevent out-of-bounds array reads.
Greedy consecutive gainsWrite this one
time O(n) · space O(1)
Iterate from day 1 to n - 1. Whenever prices[i] > prices[i - 1], add the difference prices[i] - prices[i - 1] directly to total profit. Decomposes any multi-day upward trend into a series of single-day increments.
Where people lose marks · 3
- A strictly decreasing price array must yield 0 profit; initializing profit with a negative number or selling at a loss creates errors.
- A single-day price array has no valid transactions and must return 0.
- Comparing index i with i - 1 starting the loop at index 0 leads to a negative index access.
Full solution
Greedy consecutive gains: summing every positive day-to-day difference equals the profit of buying at each valley and selling at each peak, so one O(n) pass with no pointer or boundary logic is the version to write.
Python
def max_profit_multiple(prices: list[int]) -> int:
# Every upward day is a buy-yesterday/sell-today trade; the gains sum to the same
# total as holding across the whole run, so just add each positive step.
profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
profit += prices[i] - prices[i - 1]
return profit
JavaScript
function maxProfitMultiple(prices) {
// Every upward day is a buy-yesterday/sell-today trade; the gains sum to the same
// total as holding across the whole run, so just add each positive step.
let profit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
}
return profit;
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
What each operation costs
| Operation | Time |
|---|---|
| look up element by index | O(1) |
| insert or delete at the start | O(n) |
| search an unsorted collection for a value | O(n) |
What usually goes wrong with Arrays
- Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
- Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
- Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.
Which roles need this problem
Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Arrays problems
Problem set and role mapping as of .