题目: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/#/description
1.题意
还是一只股票的n天的价格, 最多交易k次(一买一卖算一次), 能获得的最大利润是多少?
2.思路
用动态规划, dp[i][j] 表示前j天最多交易i次的最大利润, 那么答案就是dp[k][n].
每天智能做三种事情, 啥也不干 ;买进; 卖出,
dp[i][j] = max(dp[i][j-1], prices[j] + tmpMax);
,即max(啥也不干, 卖出)
tmpMax = max(tmpMax, dp[i-1][j-1] - prices[j]);
, 即 max(tmpMax, 买入)
3.代码
#ac
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
#dp[i][j] means the max profit when transaction <= i and within first j days
days=len(prices)
if(k>=days/2):
return self.fun_greedy(prices)
else:
return self.fun_dp(k, prices)
def create2dArr(self,rowNum,columnNum):
arr = [[0]*columnNum for i in range(rowNum)]
return arr
def fun_dp(self,k,prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
#dp[i][j] means the max profit when transaction <= i and within first j days
days=len(prices)
dp=self.create2dArr(k+1, days)
for i in range(1,k+1):
tmpMax=dp[i-1][0]-prices[0]
for j in range(1,days):
dp[i][j] = max(dp[i][j-1], prices[j] + tmpMax);
tmpMax = max(tmpMax, dp[i-1][j-1] - prices[j]);
return dp[k][days-1];
def fun_greedy(self,prices):
"""
:type prices: List[int]
:rtype: int
"""
answer=0
for i in range(len(prices)-1):
delta=prices[i+1]-prices[i]
answer=answer+delta if delta>0 else answer;
return answer;
4. 测试用例
print Solution().maxProfit(2, [1,2 ,3, 5, 6, 1, 7])