Best time to buy and sell stock IV

Dynamic Programming DP on stocks Medium
  • This problem and its solutions form the core logic behind many financial and trading software systems, especially algorithmic trading and robo-advisors
  • These applications aim to make profit through efficient and intelligent buying and selling of shares
  • They use similar dynamics to stipulate how many transactions can be executed, based on which stocks to hold, and for how long, in order to achieve maximum profit
  • They use such algorithms to gather, analyze and implement strategic trading decisions based on the changing market scenarios

Given an array, arr, of n integers, where arr[i] represents the price of the stock on an ith day, determine the maximum profit achievable by completing at most k transactions in total. Holding at most one share of the stock at any given time is allowed, meaning buying and selling the stock k times is permitted, but the stock must be sold before buying it again. Buying and selling the stock on the same day is allowed.

Examples:

Input: arr = [3, 2, 6, 5, 0, 3], k = 2

Output: 7

Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6 - 2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3 - 0 = 3. Total profit is 4 + 3 = 7.

Input: arr = [1, 2, 4, 2, 5, 7, 2, 4, 9, 0], k = 3

Output: 15

Explanation: Buy on day 1 (price = 1) and sell on day 3 (price = 4), profit = 4 - 1 = 3. Then buy on day 4 (price = 2) and sell on day 6 (price = 7), profit = 7 - 2 = 5. Then buy on day 7 (price = 2) and sell on day 9 (price = 9), profit = 9 - 2 = 5. Total profit is 3 + 5 + 7 = 15.

Input: arr = [1, 3, 2, 8, 4, 9], k = 2

Constraints

  • 1 <= n<= 103
  • 0 <= arr[i] <= 104
  • 0 <= k <= 100

Hints

  • "We define a DP table where: dp[i][j] → The maximum profit achievable using at most j transactions on the i-th day. The core transition formula: dp[i][j] = max(dp[i-1][j], max(arr[i] - arr[m] + dp[m][j-1]) for m in range(0, i))"
  • "Instead of iterating over all possible buy days (m), we can track the best time to buy dynamically: Maintain max_diff = max(max_diff, dp[i-1][j-1] - arr[i-1]) Update the transition equation: dp[i][j] = max(dp[i-1][j], arr[i] + max_diff)"

Company Tags

eBay Bloomberg Zomato Splunk Philips Healthcare Lyft Zoho HCL Technologies Riot Games Wayfair Texas Instruments Rakuten Broadcom Electronic Arts AMD DoorDash NVIDIA OYO Rooms JPMorgan Chase McKinsey & Company Salesforce Chewy Instacart IBM Cerner Google Microsoft Amazon Meta Apple Netflix Adobe