Trying to solve this: Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Solution: What i am doing is divide and conquer kind of approach.
dp[i][j] is the maximum profit between ith and jth day.Calculated as below:
dp[i][j] = max(dp[i][j], max(prices[i] - prices[j], dp[k][j], dp[i][k+1])), where k is less than i and greater than j.
Now all we need is below to find out the maximum profit in two transactions:
m = max(m, max(dp[i][j], dp[k][j] + dp[i][k+1]))
Please give me just hint to solve this problem as the existing solution presented here is timing out.
class Solution(object):
def profit(self, prices, dp):
m = 0
for w in range(1, len(prices)):
for i in range(1, len(prices)):
for j in range(i-w, i):
if i-w < 0:
continue
for k in range(j, i):
dp[i][j] = max(dp[i][j], max(prices[i] - prices[j], dp[k][j], dp[i][k+1]))
m = max(m, max(dp[i][j], dp[k][j] + dp[i][k+1]))
return m
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
dp = [[0 for i in range(len(prices)+1)] for i in range(len(prices)+1)]
return self.profit(prices, dp)