Best time to buy and sell stock III

Dynamic Programming DP on stocks Medium
  • This programming problem is helpful in simulating the decision-making process of trading algorithms used in fintech applications and robo-advisers
  • By answering this problem, developers can enhance their understanding of dynamic programming, which is useful in creating algorithms that can analyze historical market data, trace multiple trading scenarios, and devise optimal selling & buying strategy to maximize profits
  • This forms the backbone of several stock market forecasting software and automated trading systems, which aim to provide the most profitable trades by considering the frequency and timing of transactions

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 two transactions in total.


Holding at most one share of the stock at any time is allowed, meaning buying and selling the stock twice 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 = [4, 2, 7, 1, 11, 5]

Output: 15

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

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

Output: 12

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

Input: arr = [5, 7, 2, 10, 6, 9]

Constraints

  • 1 <= n<= 105
  • 0 <= arr[i] <= 106

Hints

  • "We define four states: first_buy → The maximum profit after the first buy. first_sell → The maximum profit after the first sell. second_buy → The maximum profit after the second buy. second_sell → The maximum profit after the second sell."
  • "For each day's stock price arr[i], update the states as follows: first_buy = max(first_buy, -arr[i]). first_sell = max(first_sell, first_buy + arr[i]) second_buy = max(second_buy, first_sell - arr[i]) second_sell = max(second_sell, second_buy + arr[i])"

Company Tags

Oracle Docker Seagate Technology Dropbox eBay Instacart Broadcom Zomato IBM Robinhood Micron Technology Salesforce Rakuten Ernst & Young Nutanix Airbnb Databricks Zynga Chewy PayPal Goldman Sachs Shopify Qualcomm AMD Ubisoft Google Microsoft Amazon Meta Apple Netflix Adobe