Solving Leetcode Interviews in Seconds with AI: Best Time to Buy and Sell Stock with Cooldown
Introduction
In this blog post, we will explore how to solve the LeetCode problem "309" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). Example 1: Input: prices = [1,2,3,0,2] Output: 3 Explanation: transactions = [buy, sell, cooldown, buy, sell] Example 2: Input: prices = [1] Output: 0 Constraints: 1 <= prices.length <= 5000 0 <= prices[i] <= 1000
Explanation
Here's the breakdown of the solution:
Dynamic Programming: We use dynamic programming to solve this problem. We maintain three states for each day:
buy,sell, andcooldown.State Transitions: We derive the recurrence relations for each state.
buy[i]represents the maximum profit we can have if we buy stock on dayi.sell[i]represents the maximum profit if we sell stock on dayi.cooldown[i]represents the maximum profit if we are in cooldown on dayi.Optimal Solution: The maximum profit at the end of the process is the maximum of
sell[n-1]andcooldown[n-1], because we can't hold the stock at the end.Time and Space Complexity: O(n) time complexity, O(n) space complexity.
Code
def maxProfit(prices):
"""
Calculates the maximum profit achievable with multiple transactions with a cooldown period.
Args:
prices: A list of stock prices for each day.
Returns:
The maximum profit achievable.
"""
n = len(prices)
if n <= 1:
return 0
buy = [0] * n
sell = [0] * n
cooldown = [0] * n
buy[0] = -prices[0]
sell[0] = 0
cooldown[0] = 0
for i in range(1, n):
buy[i] = max(cooldown[i - 1] - prices[i], buy[i - 1])
sell[i] = buy[i - 1] + prices[i]
cooldown[i] = max(cooldown[i - 1], sell[i - 1])
return max(sell[n - 1], cooldown[n - 1])