PPractick

DSA interview question

Best Time to Buy and Sell Stock II

Medium · Algorithms · Topics: dynamic programming, greedy, array

The problem

Your trading bot backend just got its most relaxed ruleset yet — no fee, no cooldown, no transaction limit. Given an array prices where prices[i] is the stock price on day i, you can buy and sell as many times as you want, but you must hold at most one share at a time (sell before buying again). Return the maximum profit achievable.

Function signature

int maxProfit(vector<int>& prices);

Test cases

Input pricesOutputExplanation
[7,1,5,3,6,4]7Buy@1,sell@5 (4), buy@3,sell@6 (3) → total 7
[1,2,3,4,5]4Buy@1, sell@5 — one continuous uptrend, capture the whole rise
[7,6,4,3,1]0Strictly decreasing — no profitable trade
[1]0Single day — no transaction possible
[]0Empty array
[1,7,2,3,6,7,6,7]13Buy@1,sell@7(6), buy@2,sell@3(1), buy@6,sell@7(1)... verify total with code

(Always verify: with unlimited transactions and no fee, capturing every single positive day-to-day delta is always optimal — confirm this intuition matches brute force before trusting the greedy.)

How interviewers phrase it

Clarifying questions to ask

  1. Can I hold at most one share at a time (must sell before buying again)?
  2. Is there any transaction fee, or is this purely unconstrained?
  3. Can I buy and sell on the same day (net zero effect), or is that disallowed entirely?
  4. What's the expected size of prices? (Confirms O(n) greedy is expected, not something more complex.)
  5. Are prices guaranteed non-negative integers?

Follow-ups to expect

  1. "Can you prove the greedy approach is optimal?"
  2. "What if there's a transaction fee?"
  3. "What if there's a cooldown after selling?"
  4. "What if there's a cap of k transactions?"
  5. "Can you solve this with DP instead of greedy, to build intuition for the constrained variants?"
  6. "What's the maximum possible number of transactions in the worst case?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in