Best Time to Buy and Sell Stock V - Problem

You are given an integer array prices where prices[i] is the price of a stock in dollars on the i-th day, and an integer k.

You are allowed to make at most k transactions, where each transaction can be either of the following:

  • Normal transaction: Buy on day i, then sell on a later day j where i < j. You profit prices[j] - prices[i].
  • Short selling transaction: Sell on day i, then buy back on a later day j where i < j. You profit prices[i] - prices[j].

Note that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.

Return the maximum total profit you can earn by making at most k transactions.

Input & Output

Example 1 — Basic Case with k=2
$ Input: prices = [2,4,1,3], k = 2
Output: 5
💡 Note: Best strategy: Buy at price 2, sell at 4 (profit +2), then short sell at 4, buy back at 1 (profit +3). Total profit = 2 + 3 = 5.
Example 2 — Single Transaction
$ Input: prices = [3,1,4,2], k = 1
Output: 3
💡 Note: One transaction: Buy at price 1, sell at price 4 for profit of 3. Alternatively, short sell at 3, buy back at 1 for same profit.
Example 3 — No Profit Possible
$ Input: prices = [1,1,1,1], k = 2
Output: 0
💡 Note: All prices are the same, so no profit can be made from any transaction.

Constraints

  • 1 ≤ prices.length ≤ 1000
  • 0 ≤ prices[i] ≤ 1000
  • 0 ≤ k ≤ 100

Visualization

Tap to expand
INPUTprices = [2, 4, 1, 3]k = 2 transactions2413Day 0Day 1Day 2Day 3Actions Available:• Buy → Sell (normal)• Short → Cover (short selling)Goal: Max profit with ≤2 transactionsALGORITHM1Define DP statesdp[day][transactions][position]2Track three positionsCash, Holding Long, Holding Short3State transitionsBuy: -price, Sell: +price4Space optimizationUse rolling arrays O(k) spaceDP Table ExampleState(day=1, k=1) = 2State(day=3, k=2) = 5Optimal: buy@2, sell@4, short@4, cover@1RESULTMaximumProfit5Optimal Strategy:Transaction 1: Buy@2, Sell@4 → +2Transaction 2: Short@4, Cover@1 → +3Total Profit: 2 + 3 = 5Time: O(n×k)Space: O(k)Key Insight:Dynamic programming with state tracking enables both normal and short selling transactions.Space optimization reduces memory from O(n×k) to O(k) using rolling arrays.TutorialsPoint - Best Time to Buy and Sell Stock V | Dynamic Programming
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 18
32.0K Views
Medium Frequency
~35 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen