122. Best Time to Buy and Sell Stock II
mediumAsked at JPMorganSame setup as LC 121, but you may buy and sell as many times as you like (no more than one stock at a time). JPMorgan asks this as the natural follow-up on equities and markets-tech loops to test whether you can spot the 'sum every positive day-over-day delta' insight.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in JPMorgan loops.
- Glassdoor (2026-Q1)— JPMorgan equities-tech onsite reports cite this as a natural follow-up to LC 121.
- LeetCode (2026-Q1)— Tagged JPMorgan on the company tag page (premium).
- Reddit r/cscareerquestions (2025-11)— JPMC SDE onsite write-up: 'they asked LC 121 then asked what changes for unlimited transactions'.
Problem
You are given an integer array prices where prices[i] is the price of a given stock on the i-th day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.
Constraints
1 <= prices.length <= 3 * 10^40 <= prices[i] <= 10^4
Examples
Example 1
prices = [7,1,5,3,6,4]7Explanation: Buy day 2 sell day 3 (4) + buy day 4 sell day 5 (3) = 7.
Example 2
prices = [1,2,3,4,5]4Explanation: Buy day 1 sell day 5; or equivalently sum every positive delta: 1+1+1+1 = 4.
Example 3
prices = [7,6,4,3,1]0Explanation: Monotonically decreasing — no profitable trade.
Approaches
1. Greedy: sum every positive delta (optimal)
Profit = sum of (prices[i] - prices[i-1]) for every i where the delta is positive. Each positive day-over-day delta is independently capturable.
- Time
- O(n)
- Space
- O(1)
function maxProfit(prices) {
let total = 0;
for (let i = 1; i < prices.length; i++) {
const delta = prices[i] - prices[i - 1];
if (delta > 0) total += delta;
}
return total;
}Tradeoff: O(n) time, O(1) space — provably optimal. Any longer up-run can be decomposed into its day-by-day deltas without losing profit because the unlimited-trade rule lets you 'restart' between any two adjacent days.
2. State-machine DP (more general)
Two states: cash (no holdings today) and hold (long one share today). Transition by buying/selling. Final answer is cash[n-1].
- Time
- O(n)
- Space
- O(1) with rolling vars
function maxProfitDP(prices) {
let cash = 0;
let hold = -prices[0];
for (let i = 1; i < prices.length; i++) {
const prevCash = cash;
cash = Math.max(cash, hold + prices[i]);
hold = Math.max(hold, prevCash - prices[i]);
}
return cash;
}Tradeoff: Same asymptotic cost but generalises cleanly to LC 123, 188, 309, 714. Worth knowing because JPMorgan's k-transaction and cooldown follow-ups all sit on top of this skeleton.
JPMorgan-specific tips
JPMorgan interviewers ask this immediately after LC 121 to test whether you spot the greedy decomposition. The strongest answers also reframe it as the state-machine DP and explain that LC 121, 122, 123, 188, 309 are all variants of the same buy/sell automaton — that fluency is what gets you the LC 188 follow-up on a senior loop.
Common mistakes
- Searching for one optimal pair of long up-runs instead of summing every positive delta (over-thinks the problem).
- Forgetting that you can buy and immediately sell on the same day (the problem statement explicitly allows it).
- Tracking 'holding' as a boolean and forgetting to track cost basis when transactioning into hold state.
- Using the LC 121 single-min approach (which assumes one transaction) and getting wrong answers on multi-peak prices.
Follow-up questions
An interviewer at JPMorgan may pivot to one of these next:
- What if you can do at most k transactions? (LC 188.)
- What if there is a cooldown of one day after each sell? (LC 309.)
- What if each transaction incurs a fixed fee? (LC 714 — subtract the fee from each delta and only take if positive after fee.)
- What if you must report running max profit after every tick? (Maintain cash + hold incrementally — same loop, just emit cash on every step.)
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
Why is the greedy 'sum positive deltas' approach optimal?
Suppose the optimal solution buys at day a and sells at day b with a < b. The profit prices[b] - prices[a] telescopes into the sum of (prices[i] - prices[i-1]) for a < i <= b. Any negative delta in that range can be 'erased' by selling before it and buying after, never reducing profit. So sum of positives is at least as good as any pair-based strategy.
Does JPMorgan accept the state-machine DP framing on the first answer?
Yes — and on senior loops they often prefer it because it generalises to the k-transaction and cooldown follow-ups they keep in their back pocket. Lead with the greedy explanation for brevity, then mention the DP framing if the interviewer probes for generality.
Free learning resources
Curated free links for this problem.
Practice these live with InterviewChamp.AI
Drill Best Time to Buy and Sell Stock II and other JPMorgan interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →