Best Time to Buy and Sell Stock
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Stock trading problems model financial decisions as transitions between discrete states. You track states like holding a share or remaining uninvested across sequential trading days.
Single Trade and Unlimited Trades
The single trade variant allows buying once and selling once on a later day. You track the lowest price seen so far and check potential profit each day.
Example 1 · Single Transaction Profit
public class StockSingleTrade { public static int maxProfit(int[] prices) { if (prices == null || prices.length == 0) return 0; int minPrice = prices[0]; int maxProfit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] < minPrice) { minPrice = prices[i]; } else { int profit = prices[i] - minPrice; if (profit > maxProfit) { maxProfit = profit; } } } return maxProfit; }
public static void main(String[] args) { int[] prices1 = {7, 1, 5, 3, 6, 4}; System.out.println("Max single profit: " + maxProfit(prices1)); int[] prices2 = {7, 6, 4, 3, 1}; System.out.println("Max single profit (descending): " + maxProfit(prices2)); }}Max single profit: 5 Max single profit (descending): 0
What this code does
- Tracking minimum purchase price allows evaluating profit at each sell day.
- Descending prices yield zero profit because buying always results in a loss.
- The algorithm processes the array in O(n) time and O(1) auxiliary space.
Example 2 · Unlimited Trades and Transaction Fee
public class StockMultiAndFee { public static int maxProfitUnlimited(int[] prices) { int totalProfit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) { totalProfit += prices[i] - prices[i - 1]; } } return totalProfit; }
public static int maxProfitWithFee(int[] prices, int fee) { if (prices == null || prices.length == 0) return 0; int hold = -prices[0]; int free = 0; for (int i = 1; i < prices.length; i++) { int prevHold = hold; hold = Math.max(hold, free - prices[i]); free = Math.max(free, prevHold + prices[i] - fee); } return free; }
public static void main(String[] args) { int[] prices = {1, 3, 2, 8, 4, 9}; System.out.println("Unlimited trades profit: " + maxProfitUnlimited(prices)); System.out.println("Trades with fee 2 profit: " + maxProfitWithFee(prices, 2)); }}Unlimited trades profit: 13 Trades with fee 2 profit: 8
What this code does
- Unlimited trades sum all upward price differences across consecutive days.
- The fee variant maintains hold and free states, subtracting the fee on sale.
- Both methods run in O(n) time and consume strictly O(1) auxiliary memory.
The unlimited trades variant permits buying and selling multiple times. You capture profit from every upward price movement between consecutive days. Both problems can run in linear time with constant auxiliary space.
State Machine DP Modeling
A state machine models decisions as movements between defined conditions. At each step, an investor either holds a stock or remains free of stock.
Let hold represent the maximum profit while holding one share. Let free represent the maximum profit while holding zero shares.
Each day updates these states based on buying, selling, or holding steady.
Step by step
Step 1 of 5
- day
- 0
- price
- 1
- hold
- -1
- free
- 0
Cooldown and Transaction Fee Variations
With a cooldown rule, selling requires waiting one full day before buying again. This constraint adds a third distinct state representing cooldown rest.
With a transaction fee, every completed trade incurs an explicit cost. You subtract this fee either when opening or closing the transaction.
Example 3 · Stock Trading with Cooldown
public class StockWithCooldown { public static int maxProfit(int[] prices) { if (prices == null || prices.length <= 1) return 0; int hold = -prices[0]; int sold = 0; int rest = 0; for (int i = 1; i < prices.length; i++) { int prevHold = hold; int prevSold = sold; hold = Math.max(hold, rest - prices[i]); sold = prevHold + prices[i]; rest = Math.max(rest, prevSold); } return Math.max(sold, rest); }
public static void main(String[] args) { int[] prices1 = {1, 2, 3, 0, 2}; System.out.println("Max profit with cooldown: " + maxProfit(prices1)); int[] prices2 = {1}; System.out.println("Single day profit: " + maxProfit(prices2)); }}Max profit with cooldown: 3 Single day profit: 0
What this code does
- Three states model holding a stock, selling today, and resting after a sale.
- Buying requires transitioning from rest, enforcing the mandatory cooldown.
- The loop updates all three scalar states in O(n) time and O(1) space.
Both rules modify state transitions without increasing asymptotic time complexity.
Space Optimization Across States
Each state at day i depends solely on values from day i - 1. You do not need full arrays to store history.
A few primitive scalar variables suffice to track states across the trading timeline.
This optimization reduces memory consumption from O(n) down to strictly O(1) space.
Next step
Check your understanding
10 quick questions