Best time to buy and sell stock II

Dynamic Programming DP on stocks Medium
  • This problem is a classic example of a scenario in algorithmic trading software, which is extensively used in finance and investment fields
  • Such software helps make data-driven decisions and automate multiple trades; they can execute more efficient trades than a human trader
  • The ability to detect and leverage profit-making opportunities like the one described in this problem is a critical function in these systems
  • The problem is essentially defining the peak-valley approach, a common practice in trend-following trading strategies
  • Algorithmic trading systems use similar logic but on a much more complex and vast scale
  • They often include elements like volatility prediction, pattern recognition, and high-frequency trading

Given an array arr of n integers, where arr[i] represents price of the stock on the ith day. Determine the maximum profit achievable by buying and selling the stock any number of times.


Holding at most one share of the stock at any given time is allowed, meaning buying and selling the stock can be done any number of times, but the stock must be sold before buying it again. Buying and selling the stock on the same day is permitted.

Examples:

Input: arr = [9, 2, 6, 4, 7, 3]

Output: 7

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

Input: arr = [2, 3, 4, 5, 6]

Output: 4

Explanation: Buy on day 1 (price = 2) and sell on day 5 (price = 6), profit = 6 - 2 = 4. Total profit is 4.

Input: arr = [8, 6, 5, 4, 3]

Constraints

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

Hints

  • "Define the DP states as follows: dp[i][0] → Maximum profit on the i-th day without holding a stock. dp[i][1] → Maximum profit on the i-th day while holding a stock."
  • Since dp[i] only depends on dp[i-1], we can reduce space complexity from O(n) to O(1) by maintaining only two variables instead of an entire DP table.

Company Tags

Walmart Flipkart Pinterest Mastercard Visa Broadcom Bloomberg Teladoc Health Morgan Stanley Salesforce DoorDash Deloitte Bungie Medtronic Texas Instruments Wayfair Splunk Oracle Nutanix Unity Technologies Rakuten HashiCorp Goldman Sachs Zynga Swiggy Google Microsoft Amazon Meta Apple Netflix Adobe